Search code examples
androidconnectivity

Checking internet connection in Android (function comparison)


So I am comparing which of the two functions I should implement below. I know one checks if the phone is connected to the internet vs. checks if you have a connection in general? Does one work better then the other, what does one do vs. the other? Do they do the same thing?

Function 1:

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;
}

Function 2:

private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager 
    = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null;
}

Solution

  • Firstly, function 1. requires permission

    <uses-permission android:name="android.permission.INTERNET"/>
    

    Function 2. needs

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    

    Function 1.

    • Transfers actual data (bad)
    • Doesn't work if DNS servers are dead
    • Doesn't work if Google is down (small chance, but not 0%)
    • On slow mobile networks, may take quite some time before you get the response (really bad)

    In practice, you should only use function 2. and properly handle failed requests to YOUR server