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?
You are right. The code you've provided only checks if there is a network connection. The best way to check if there is an active Internet connection is to try and connect to a known server via http.
Of course you can substitute the
http://www.google.com
URL for any other server you want to connect to, or a server you know has a good uptime.As Tony Cho also pointed out in this comment below, make sure you don't run this code on the main thread, otherwise you'll get a NetworkOnMainThread exception (in Android 3.0 or later). Use an AsyncTask or Runnable instead.
If you want to use google.com you should look at Jeshurun's modification. In his answer he modified my code and made it a bit more efficient. If you connect to
and then check the responsecode for 204
then you don't have to fetch the entire google home page first.
return true if internet is actually available
Make sure you have these two permission
try this one
Hope the above code helps you, also make sure you have internet permission in ur app.
You don't necessarily need to make a full HTTP connection. You could try just opening a TCP connection to a known host and if it succeeds you have internet connectivity.
Then just check with:
The latest way to do that from the documentation is to use the
ConnectivityManager
to query the active network and determine if it has Internet connectivity.Add these two permissions to your AndroidManifest.xml file: