Hi all I need to verify if my device is currently connected to internet or not and so I wrote this class that uses a ConnectivityManager
to check:
public boolean checkInternetConnection() {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isAvailable() && cm.getActiveNetworkInfo().isConnected()) {
return true;
} else {
return false;
}
}
works great, because right now the method is in a class in the main package (com.App
), but how should I change the code to make it work in a class defined in com.App.Utility
?
Thanks!
Try this , this code works.
The only issue with using getActiveNetworkInfo() is that there are a number of situations where is will not correctly detect connectivity. For example if the mobile network is disabled on a phone but wifi is available then the active network may still be counted as the mobile network and therefore return false.
An alternative is:
Thx Alan H!
The if condition may cause NPE when one of netInfoMob and netInfoWifi is null but the other not.
This one works for me: