Skip to content

Instantly share code, notes, and snippets.

@truedem
Created August 3, 2016 21:28
Show Gist options
  • Save truedem/1192f011388cd23eb06909f33fa3aa77 to your computer and use it in GitHub Desktop.
Save truedem/1192f011388cd23eb06909f33fa3aa77 to your computer and use it in GitHub Desktop.
Android code to check if both network and Internet connections are available
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