Created
August 3, 2016 21:28
-
-
Save truedem/1192f011388cd23eb06909f33fa3aa77 to your computer and use it in GitHub Desktop.
Android code to check if both network and Internet connections are available
This file contains hidden or 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
public static boolean isNetworkAvailable() { | |
// ConnectivityManager connectivityManager = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE); | |
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); | |
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); | |
return activeNetworkInfo != null && activeNetworkInfo.isConnected(); | |
} | |
public static boolean isInternetAvailable () { | |
if (isNetworkAvailable()) { | |
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); // possible execution delay | |
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