Skip to content

Instantly share code, notes, and snippets.

@amilcar-sr
Last active May 29, 2018 00:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amilcar-sr/773f3f2bf087edeed714bc1ab6e4c056 to your computer and use it in GitHub Desktop.
Save amilcar-sr/773f3f2bf087edeed714bc1ab6e4c056 to your computer and use it in GitHub Desktop.
package com.yourpackage.example;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class NetworkUtils {
private final static String TAG = NetworkUtils.class.getName();
public static boolean hasInternetConnection(Context context) {
if (isNetworkAvailable(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;
} catch (IOException e) {
Log.e(TAG, "Error checking internet connection", e);
}
} else {
Log.d(TAG, "No network available!");
}
return false;
}
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnected();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment