I need to display an alert screen when the device is losing network connectivity. When connectivity is back, I hide this alert. I'm using ConnectivityManager.NetworkCallback() to determine connectivity status. The app is being run on API 22 devices.
public void registerNetworkAvailability(final Context context, BroadcastReceiver networkAvailabilityReceiver) {
context.registerReceiver(networkAvailabilityReceiver, new IntentFilter(NETWORK_AVAILABILITY_ACTION));
connectivityManager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
NetworkRequest.Builder builder = new NetworkRequest.Builder();
networkCallback = new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(Network network) {
context.sendBroadcast(getNetworkAvailabilityIntent(true));
}
@Override
public void onLost(Network network) {
if (!isAvailable(context))
context.sendBroadcast(getNetworkAvailabilityIntent(false));
}
};
connectivityManager.registerNetworkCallback(builder.build(), networkCallback);
}
It's registered in onCreate() method of my Activity
networkAvailability = NetworkAvailability.getInstance();
networkAvailability.registerNetworkAvailability(this, receiver);
And here is BroadcastReceiver
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent == null) return;
boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
if (noConnectivity) {
connectivityError = true;
showNetworkAlert();
} else {
NetworkInfo networkInfo = networkAvailability.getActiveNetworkInfo(getApplicationContext());
if (networkInfo != null) {
networkType = networkInfo.getType();
Logger.i(TAG, "connection type: " + networkInfo.getTypeName());
Logger.i(TAG, "connection IP: " + networkAvailability.getLocalIpAddress());
}
if (connectivityError) {
connectivityError = false;
showDialog(null);
initConfiguration();
}
}
if (updateDialog != null) {
updateDialog.dismiss(null);
updateDialog = null;
}
}
};
Usually, onAvailable()
is being called 1-2 times after Wi-Fi is connected. But for some places where the app is running, there are multiple onAvailable()
callbacks arriving every minute.
07-07 14:13:12.074 7343 7343 connection type: WIFI
07-07 14:13:12.077 7343 7343 connection IP: 192.168.1.216
07-07 14:13:24.160 7343 7343 connection type: WIFI
07-07 14:13:24.164 7343 7343 connection IP: 192.168.1.216
07-07 14:13:33.268 7343 7343 connection type: WIFI
07-07 14:13:33.278 7343 7343 connection IP: 192.168.1.216
07-07 14:13:45.409 7343 7343 connection type: WIFI
07-07 14:13:45.418 7343 7343 connection IP: 192.168.1.216
07-07 14:13:54.500 7343 7343 connection type: WIFI
07-07 14:13:54.512 7343 7343 connection IP: 192.168.1.216
This is affecting app performance, making the UI slow and unresponsive.
What may be the reason for that? How to improve performance in this case?