手机的网络状态监听:
android系统已经有这样一个动作,当手机的网络状态发生改变时,发送一个广播;
所以我只需要做的步骤是:
1、添加允许获取网络切换的状态权限:<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
添加网络连接的权限:<uses-permission android:name="android.permission.INTERNET" />
2、在AndroidMainifest.xml中注册该广播接收者:
清单文件注册:
<receiver android:name="com.example.newwork.NetworkReceiver" >
<intent-filter>
<!-- 监听的动作类型,这里是监听网络连接的状态 -->
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
代码注册:
NetworkChangedReceiver networkChangedReceiver = new NetworkChangedReceiver();
IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(networkChangedReceiver, intentFilter);
警告:
清单文件注册不能适配android7.0及以上(targetSdkVersion ≥ N,清单文件注册失效,亲测没有收到广播)
3.自定义BrodCaseReceiver:
public class NetworkReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeInfo = manager.getActiveNetworkInfo();
//如果无网络连接activeInfo为null
//也可获取网络的类型
if (activeInfo != null) { //网络连接
Toast.makeText(context, "测试:网络连接成功",0).show();
} else { //网络断开
Toast.makeText(context, "测试:网络断开",0).show();
}
}
}