I am working on app where I do need to check if Internet connection is stabilized or not. If Internet connection is not stabilized then we need to call our web service else we will not hit that.
For that I wrote following Broadcast receiver in Java since I read that android now want developer to register this receiver in Java class.
so here it is
private class NetworkChangeBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
callMyWebService();
}
@Override
protected void onResume() {
super.onResume();
if (!isNetworkBroadcastReceiverRegistered) {
if (NetworkChangeBR == null) {
NetworkChangeBR = new NetworkChangeBroadcastReceiver();
registerReceiver(NetworkChangeBR, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
isNetworkBroadcastReceiverRegistered = true;
}
}
acquireWakeLock(mCustomSharedPreferences.getBoolean(CustomSharedPreferences.KEEP_SCREEN_ON_ALL_THE_TIME, false));
}
@Override
protected void onPause() {
super.onPause();
if (isNetworkBroadcastReceiverRegistered) {
unregisterReceiver(NetworkChangeBR);
NetworkChangeBR = null;
isNetworkBroadcastReceiverRegistered = false;
}
}
Problems: But I face following problems
Please help me in both cases.
The reason that your BroadcastReceiver
is immediately triggered is because the broadcast Intent
ConnectivityManager.CONNECTIVITY_ACTION
is a "sticky" broadcast. This allows apps to register for and receive immediately the last broadcast event of this type (so that they can determine the current connectivity situation). If this "sticky" broadcast is causing you problems, just check for that in onReceive()
and ignore it:
// Ignore the sticky broadcast of the initial state
if (isInitialStickyBroadcast()) {
return;
}
There is a lot of data passed as "extras" in the Intent
that your BroadcastReceiver
gets. You can tell, for example, if the event is a CONNECT or a DISCONNECT event, etc. Check the documenttion on ConnectivityManager
to determine what "extras" are sent and how to use them.