Android 监听网络变化

广播监听,使用动态注册方法

1、在mainifest注册

 

2、继承broadcastReceiver

 class NetworkChangeReceiver extends BroadcastReceiver
    {
        @Override
        public void onReceive(Context context, Intent intent)
        {
            ConnectivityManager connectionManager = (ConnectivityManager)
                    context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connectionManager.getActiveNetworkInfo();
            if (networkInfo != null && networkInfo.isAvailable()) {
                Toast.makeText(context, R.string.networkAvailable, Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(context, R.string.networkUnavailable, Toast.LENGTH_SHORT).show();
            }
        }
    }

3、在activity里的onCreate()注册广播


 IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        networkChangeReceiver = new NetworkChangeReceiver();
        registerReceiver(networkChangeReceiver, intentFilter);

4、在activity里的onDestroy()取消广播


 unregisterReceiver(networkChangeReceiver);

 

你可能感兴趣的:(android)