加入权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
创建了一个IntentFilter的实例,并给它添加一个值,"android.net.conn.CONNECTIVITY_CHANGE"的action
当网络状态发生变化时,系统发出的证书一条值为android.net.CONNECTIVITY_CHANGE的广播,广播接收器想要监听什么广播,就在这里添加相应的action.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intentFilter = new IntentFilter();
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
networkChangeReceiver = new NetworkChangeReceiver();
registerReceiver(networkChangeReceiver,intentFilter);
}
动态注册的广播接收器一定都要取消注册
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(networkChangeReceiver);
}
在MainActivity 中定义一个内部类NetworkChangeReceiver,继承BroadcastReceiver,并重写onReceive方法,每当网络发生变化时
onReceive就会执行
class NetworkChangeReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetworkInfo!=null && activeNetworkInfo.isAvailable()){
Toast.makeText(context, "network is available", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, "network is unavailable", Toast.LENGTH_SHORT).show();
}
}
}