Broadcastreceiver For Connectivity_action Always Returns Null In Intent.getextras()
Im trying to receive BroadcastMessages from CONNECTIVITY_ACTION: // register BroadcastReceiver on network state changes final IntentFilter mIFNetwork = new IntentFilter();
Solution 1:
You can not get extra but you can get data by this way
privateclassConnectivityBroadcastReceiverextendsBroadcastReceiver {
@OverridepublicvoidonReceive(Context context, Intent intent) {
booleannoConnectivity= intent.getBooleanExtra(ConnectivityManager
.EXTRA_NO_CONNECTIVITY, false);
NetworkInfoinfo1= (NetworkInfo) intent.getParcelableExtra(ConnectivityManager
.EXTRA_NETWORK_INFO);
NetworkInfoinfo2= (NetworkInfo) intent.getParcelableExtra(ConnectivityManager
.EXTRA_OTHER_NETWORK_INFO);
Stringreason= intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
booleanfailOver= 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
Solution 2:
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:
privateclassConnectivityBroadcastReceiverextendsBroadcastReceiver {
@OverridepublicvoidonReceive(Context context, Intent intent) {
unregisterReceiver(this)
checkConnection();
}
}
privatevoidcheckConnection() {
ConnectivityManagercm= (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 :)
Post a Comment for "Broadcastreceiver For Connectivity_action Always Returns Null In Intent.getextras()"