清单文件申请权限ACCESS_NETWORK_STATE
新建广播接收者继承BroadcastReceiver,重写onReceive方法
@Override
public void onReceive(Context context,Intent intent) {
ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo =connectivityManager.getActiveNetworkInfo();
if (networkInfo !=null &&networkInfo.isAvailable()) {
//网络连接
}else {
//网络断开
}
}
MainActivity注册广播接收者
IntentFilter intentFilter =new IntentFilter();
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
networkChang =new NetChange();
registerReceiver(networkChang,intentFilter);
网络连接状态发生变化时会回调onReceive方法,通过判断发送网络是否连接的消息,在需要监听的位置接收网络发生变化的消息处理即可