通过广播监听网络状态
通过广播监听网络状态
首先声明权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
创建一个广播接收器继承自BroadcastReceiver
当对应广播到来时,就会执行 onReceive
方法
class NetworkChangeReceiver extends BroadcastReceiver {
@Override //当网络状态发生变化时执行
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectivityManager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isAvailable()) {
Toast.makeText(context, "Network is available", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Network is unavailable", Toast.LENGTH_SHORT).show();
}
}
}
创建IntentFilter实例,并添加特定action,然后注册
private IntentFilter intentFilter;
private NetworkChangeReceiver networkChangeReceiver;
//动态注册
intentFilter = new IntentFilter();
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
networkChangeReceiver = new NetworkChangeReceiver();
registerReceiver(networkChangeReceiver, intentFilter);
最后记得取消注册
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(networkChangeReceiver); //取消注册
}
文章部分内容摘自网络和图书,如有侵权,请联系我。