Skip to content

Instantly share code, notes, and snippets.

@leonardortlima
Created March 28, 2017 18:27
Show Gist options
  • Save leonardortlima/7d8aa1f1cc4015132d0af3e98428ae2c to your computer and use it in GitHub Desktop.
Save leonardortlima/7d8aa1f1cc4015132d0af3e98428ae2c to your computer and use it in GitHub Desktop.
private static boolean hasNetwork(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
public static boolean canAccessInternet(Context context) {
if (hasNetwork(context)) {
try {
HttpURLConnection conn = (HttpURLConnection)
(new URL("http://clients3.google.com/generate_204").openConnection());
conn.setRequestProperty("User-Agent", "Android");
conn.setRequestProperty("Connection", "close");
conn.setConnectTimeout(1500);
conn.connect();
return (conn.getResponseCode() == 204 && conn.getContentLength() == 0);
} catch (IOException e) {
Log.e(TAG, "Error while checking internet access", e);
}
} else {
Log.d(TAG, "Network not available");
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment