I tried below code to check the connectivity:
public static NetworkInfo getNetworkInfo(Context context) {
if (context == null)
return null;
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm == null)
return null;
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected())
return activeNetwork;
else {
for (Network n: cm.getAllNetworks()) {
NetworkInfo nInfo = cm.getNetworkInfo(n);
if(nInfo != null && nInfo.isConnected())
return nInfo;
}
}
return activeNetwork;
}
public static boolean isConnectivityAllowed(Context context) {
NetworkInfo info = NetworkUtils.getNetworkInfo(context);
return info != null && info.isConnected();
}
Generally, it works fine but in some conditions, it returns disconnected although I have a connection. After searching, testing, checking the logs, I understood when the device's battery is low if I run the app, the function returns disconnected because the OS put the system on power saver and then if I change the connectivity, the app gets the right answer. More information is available here in @phil 's answer.
Does anyone know how to check the connection when power saver in on?!