BroadcastReceiver for CONNECTIVITY_ACTION always returns null in intent.getExtras()

前端 未结 2 1207
走了就别回头了
走了就别回头了 2020-12-28 21:29


Im trying to receive BroadcastMessages from CONNECTIVITY_ACTION:

    // register BroadcastReceiver on network state changes
    final IntentFilter mIFNe         


        
相关标签:
2条回答
  • 2020-12-28 22:07

    You can not get extra but you can get data by this way

    private class ConnectivityBroadcastReceiver extends BroadcastReceiver {
    
        @Override
        public void onReceive(Context context, Intent intent) {
            boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager
                    .EXTRA_NO_CONNECTIVITY, false);
            NetworkInfo info1 = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager
                    .EXTRA_NETWORK_INFO);
            NetworkInfo info2 = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager
                    .EXTRA_OTHER_NETWORK_INFO);
            String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
            boolean failOver = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);
            Log.d("MY_TAG", "onReceive(): mNetworkInfo=" + info1 + " mOtherNetworkInfo = " +
                    (info2 == null ? "[none]" : info2 + " noConn=" + noConnectivity));
        }
    }
    

    For more info see this

    http://code.google.com/p/androidwisprclient/source/browse/trunk/src/com/joan/pruebas/NetworkConnectivityListener.java?r=2

    0 讨论(0)
  • 2020-12-28 22:13

    Dharmendras answer is good. However, note that EXTRA_NETWORK_INFO is now deprecated (since Api Level 14) and the Android docs say the following:

    Since NetworkInfo can vary based on UID, applications should always obtain network information through getActiveNetworkInfo().

    That actually makes things very easy for us. You could reuse the connectivity check you probably did before and do something like this:

    private class ConnectivityBroadcastReceiver extends BroadcastReceiver {
    
        @Override
        public void onReceive(Context context, Intent intent) {
            unregisterReceiver(this)
            checkConnection();
        }
    }
    
    private void checkConnection() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo()
                .isConnectedOrConnecting()) {
            // do something
        }
    }
    

    Assuming you're inside the activity that registered the broadcast of course.

    This also has the added benefit of following the best practices for only listening for the connectivity broadcast as briefly as possible, outlined here :)

    0 讨论(0)
提交回复
热议问题