I need to tell if my device has Internet connection or not. I found many answers like:
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
(Taken from Detect whether there is an Internet connection available on Android.)
But this is not right, for example if I'm connected to a wireless network which doesn't have Internet access, this method will return true… Is there a way to tell if the device has Internet connection and not if it is only connected to something?
Based on the accepted answers, I have built this class with a listener so you can use it in the main thread:
First: InterntCheck class which checks for internet connection in the background then call a listener method with the result.
Second: instantiate an instance of the class in the main thread and wait for the response (if you have worked with Firebase api for android before this should be familiar to you!).
Now inside onComplete method you will get whether the device is connected to the internet or not.
I have modified THelper's answer slightly, to use a known hack that Android already uses to check if the connected WiFi network has Internet access. This is a lot more efficient over grabbing the entire Google home page. See here and here for more info.
If you're targeting Lollipop or higher it's possible to use the new NetworkCapabilities class, i.e: