Android: 判断网络状态

判断当前Wifi或Ethernet连接状态:

 

	public static boolean isNetworkConnected(Context context) {
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = cm.getActiveNetworkInfo();
		if (info != null) {
			int type = info.getType();
			if (type == ConnectivityManager.TYPE_WIFI || 
				type == ConnectivityManager.TYPE_ETHERNET) {
				return info.isAvailable();
			}			
		} 
		
		return false;
	}


BroadcastReceiver中监测Wifi或Ethernet连接状态:

 

 

		if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action)) {
			Bundle extras = intent.getExtras();
			if (extras != null) {
                NetworkInfo networkInfo =
                        (NetworkInfo)extras.get(ConnectivityManager.EXTRA_NETWORK_INFO);
                if (networkInfo == null) return;
                
                State state = networkInfo.getState();
                int networkType = networkInfo.getType();
            	if (networkType == ConnectivityManager.TYPE_WIFI || 
                	networkType == ConnectivityManager.TYPE_ETHERNET) {
	                if (state == State.CONNECTED) {
	                	mListener.onNetworkStateChange(true);
	                	
	                } else if (state == State.DISCONNECTED) {
	                	mListener.onNetworkStateChange(false);
	                	
	                }
            	}
                    
			}

		}


 

 

posted @ 2013-04-27 19:41  javawebsoa  Views(274)  Comments(0Edit  收藏  举报