Created
March 28, 2017 18:27
-
-
Save leonardortlima/7d8aa1f1cc4015132d0af3e98428ae2c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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