Using "getActiveNetworkInfo()" and "isConnectedOrConnecting()" will return true if the are network connectivity and not if there are a connection to internet. For example if you don't have signal and so you don't have internet it but your mobile has the data activated it will return true instead of false.
To truly check if internet is available you need to check for network connectivity and also check for internet connection!
And you can check for internet connection, for example, by trying to ping a well know address (like google in my code)
This is the code, just use this code and call isInternatAvailable(context).
private static final String CMD_PING_GOOGLE = "ping -c 1 google.com";
public static boolean isInternetAvailable(@NonNull Context context) {
return isConnected(context) && checkInternetPingGoogle();
}
public static boolean isConnected(@NonNull Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if(cm != null) {
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
} else {
return false;
}
}
public static boolean checkInternetPingGoogle(){
try {
int a = Runtime.getRuntime().exec(CMD_PING_GOOGLE).waitFor();
return a == 0x0;
} catch (IOException ioE){
EMaxLogger.onException(TAG, ioE);
} catch (InterruptedException iE){
EMaxLogger.onException(TAG, iE);
}
return false;
}