通过广播监听网络状态

通过广播监听网络状态

首先声明权限

<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);  //取消注册
    }
posted @ 2017-07-21 14:44  -Tiger  阅读(534)  评论(0编辑  收藏  举报