I have a problem with checking internet connection in android at runtime. I use some different methods to check internet connection but i don\'t know which one is better . b
To check if internet connection is available or not, you can use the below code snippet
public static boolean hasActiveInternetConnection(Context context) {
if (isNetworkAvailable(context)) {
try {
HttpURLConnection urlc = (HttpURLConnection)
(new URL("http://clients3.google.com/generate_204")
.openConnection());
urlc.setRequestProperty("User-Agent", "Android");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
return (urlc.getResponseCode() == 204 && urlc.getContentLength() == 0);
} catch (IOException e) {
Log.e(LOG_TAG, "Error checking internet connection", e);
}
} else {
Log.d(LOG_TAG, "No network available!");
}
return false;
}
This code snippet will also help you to identify whether you device is having internet connection even if you are connected through wifi network.
Note: make sure to call this method in background thread ,because this can take time depending on your network speed, and should not be called in Main thread