动态注册广播接收器,监听网络变化
1:NetChangeReceiver.java
public class NetChangeReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); if(netInfo!=null && netInfo.isAvailable()){ Toast.makeText(context, "网络已链接", Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(context, "网络未链接", Toast.LENGTH_SHORT).show(); } } }
2:MainActivity.java
public class MainActivity extends Activity { IntentFilter intentFilter; NetChangeReceiver netChangeReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); intentFilter = new IntentFilter(); //当前网络发生变化后,系统会发出一条值为android.net.conn.CONNECTIVITY_CHANGE的广播,所以要监听它 intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE"); netChangeReceiver = new NetChangeReceiver(); //进行注册 registerReceiver(netChangeReceiver, intentFilter); } @Override protected void onDestroy() { super.onDestroy(); //动态注册的广播接收器一定要进行取消注册 unregisterReceiver(netChangeReceiver); } }
3:最后不要忘记声明权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>