android 登录前检查网络状态

package com.dx;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.os.Bundle;
import android.widget.TextView;

public class Main extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.main);
        TextView textView = new TextView(this);
        textView.setText("网络检测");
        setContentView(textView);
        
        if(checkNetWorkInfo()){
        	goToNetWork();
        };
    }

	private boolean goToNetWork() {
		// TODO Auto-generated method stub
		ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = connectivityManager.getActiveNetworkInfo();
		if(info == null || !info.isAvailable()){
			new AlertDialog.Builder(this).setMessage("没有可以使用的网络").setPositiveButton("Ok", null).show();    
			return false;
		}
		else{
			new AlertDialog.Builder(this).setMessage("网络正常可以使用").setPositiveButton("Ok", null).show();    
		    return true;
		}
		
		
	}

	private boolean checkNetWorkInfo() {
		// TODO Auto-generated method stub
		ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		State wifi  = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
		if(wifi != null){
			new AlertDialog.Builder(this).setMessage(wifi.toString()).setPositiveButton("wifi", null).show();//显示wifi网络连接状态    
			return true;
			
		}else{
			State mobile  = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
			if(mobile != null){
				new AlertDialog.Builder(this).setMessage(mobile.toString()).setPositiveButton("3G", null).show();//显示3G网络连接状态    
				return true;
			}
		}
		return false;
		
	}
}
 

 

你可能感兴趣的:(android)