0

Typically when building my android applications that require API calls etc, I check the NetworkAvailability before making such calls like so:

    public boolean networkIsAvailable() {

        boolean result = false;
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager
                .getActiveNetworkInfo();
        if (activeNetworkInfo != null) {

            if (activeNetworkInfo.isConnected()) {
                result = true;

            }
        }
        return result;
    }

Simple enough... But what happens when say a user is on a device that has no Mobile Connection and is connected to a Wifi Network, but that Wifi Network doesn't have internet access.

Are there options aside from catching a java.net.UnknownHostException to test for actual internet access?

erik
  • 4,698
  • 11
  • 64
  • 111

1 Answers1

1

You can use this:

public static boolean hasActiveInternetConnection(Context context) {
    if (isNetworkAvailable(context)) {
        try {
            HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
            urlc.setRequestProperty("User-Agent", "Test");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(1500); 

            urlc.connect();
            return (urlc.getResponseCode() == 200);
       } catch (IOException e) {
            Log.e(LOG_TAG, "Error checking internet connection", e);
        }
    } else {
        Log.d(LOG_TAG, "No network available!");
    }
    return false;
}

Remember this: "As Tony Cho also pointed out in this comment below, make sure you don't run this code on the main thread, otherwise you'll get a NetworkOnMainThread exception (in Android 3.0 or later). Use an AsyncTask or Runnable instead."

Source: Detect if Android device has Internet connection

Community
  • 1
  • 1
  • thank you, I wanted to avoid actually making a network call but i guess thats really the only option aside from maybe socket testing – erik Jul 21 '14 at 12:30