Search code examples
androidandroid-internet

Testing for Internet not Network


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?


Solution

  • 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