android中检测网络是否断开

在android中,如果网络断开 ,系统会自动发送一个广播,我们要注册一个广播监听器,当收到这个广播的时候做自己的处理即可,

自己也网上找了资料,如下

http://dwtedx.com/itshare_269.html

http://bbs.9ria.com/thread-213359-1-1.html

http://blog.csdn.net/chenzheng_java/article/details/6387116


private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
		@SuppressWarnings("deprecation")
		@Override
		public void onReceive(Context context, Intent intent) {

			ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo wifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
			NetworkInfo mobile = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

			Bundle bundle = intent.getExtras();
			NetworkInfo aNetworkInfo = (NetworkInfo) bundle.get(ConnectivityManager.EXTRA_NETWORK_INFO);

			if (aNetworkInfo != null) {
				if (aNetworkInfo.isConnected()) {
					//表示网络已连接
				} else if (!wifi.isConnected() && !mobile.isConnected()) {
				
					//表示wifi和数据连接都断开了,可以弹出一个toast等
				}
			}
		}
	};


使用方法也很简单

在onResumef方法里注册这个广播

registerReceiver(mBroadcastReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));


最后记得在onPause里注销

unregisterReceiver(mBroadcastReceiver);

-------------分割线------------

20161205补充 如果不想使用广播,可以直接用下面的方法即可判断是否离线

	/** 判断是否有可用网络 */
	public static boolean existAvailableNetwork(Context context) {
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity == null) {
			return false;
		} else {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		return false;
	}



你可能感兴趣的:(android中检测网络是否断开)