Skip to content

Instantly share code, notes, and snippets.

@cesarferreira
Created July 26, 2016 09:22
Show Gist options
  • Save cesarferreira/184b73fc239cbd4fd4161414f8ba1694 to your computer and use it in GitHub Desktop.
Save cesarferreira/184b73fc239cbd4fd4161414f8ba1694 to your computer and use it in GitHub Desktop.
Check network availability
public static boolean isNetworkAvailable (Context context) {
if (connectedToTheNetwork(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(TAG, "Error checking internet connection", e);
}
} else {
Log.d(TAG, "No network available!");
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment