网络监听以及判断网络是否可用

南笙酒味 提交于 2020-02-04 19:26:38

网络监听:

AndroidManifest中定义网络监听的receiver

<receiver  

    android:name=".receiver.ConnectionChangeReceiver" >   

    <intent-filter>   

        <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>   

    </intent-filter>  

</receiver>

  

定义网路监听的广播接受类:

public class ConnectionChangeReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		if (!Utils.isNetworkConnected()) {
			NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
			notificationManager.cancel(Constants.NOTIFICATION_SYNC);
		}
	}

}

判断网络是否可用:

	public static boolean isNetworkConnected() {
		ConnectivityManager connectivity = (ConnectivityManager) DoitApplication.mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity == null) {
			// TODO 网络不可用
		} 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;
	}

  


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!