Connectivitymanager.extra_no_connectivity Is Always False On Android Lollipop
I am using this piece of code to detect Internet connection state changes. It works fine on Android<5.0, but on API 21 this: intent.getExtras().getBoolean(ConnectivityManager.EX
Solution 1:
You can use NetworkRequest added in API level 21.
Create a custom intent action:
publicstaticfinalStringCONNECTIVITY_ACTION_LOLLIPOP="com.example.CONNECTIVITY_ACTION_LOLLIPOP";
Create the new method registerConnectivityActionLollipop
:
@TargetApi(Build.VERSION_CODES.LOLLIPOP)privatevoidregisterConnectivityActionLollipop() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
return;
ConnectivityManagerconnectivityManager= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkRequest.Builderbuilder=newNetworkRequest.Builder();
connectivityManager.registerNetworkCallback(builder.build(), newConnectivityManager.NetworkCallback() {
@OverridepublicvoidonAvailable(Network network) {
Intentintent=newIntent(CONNECTIVITY_ACTION_LOLLIPOP);
intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
sendBroadcast(intent);
}
@OverridepublicvoidonLost(Network network) {
Intentintent=newIntent(CONNECTIVITY_ACTION_LOLLIPOP);
intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
sendBroadcast(intent);
}
});
}
Add the new intent action to the intent filter and call registerConnectivityActionLollipop
:
IntentFilterintentFilter=newIntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
intentFilter.addAction(CONNECTIVITY_ACTION_LOLLIPOP);
registerReceiver(mBroadcastReceiver, intentFilter);
registerConnectivityActionLollipop();
Change the BroadcastReceiver
to support the new intent action:
privateBroadcastReceivermBroadcastReceiver=newBroadcastReceiver() {
@OverridepublicvoidonReceive(Context context, Intent intent) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP && TextUtils.equals(intent.getAction(), ConnectivityManager.CONNECTIVITY_ACTION) ||
Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && TextUtils.equals(intent.getAction(), CONNECTIVITY_ACTION_LOLLIPOP)) {
if (intent.getExtras() != null) {
finalConnectivityManagerconnectivityManager= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
finalNetworkInfonetworkInfo= connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnectedOrConnecting()) {
Log.d("receiver test", "detected on");
}
}
Log.d("receiver test", Boolean.toString(intent.getExtras().getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY)));
if (intent.getExtras().getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY, Boolean.FALSE)) {
Log.d("receiver test", "detected off");
}
}
}
};
Post a Comment for "Connectivitymanager.extra_no_connectivity Is Always False On Android Lollipop"