Sunday 27 September 2015

Android: How to check that the device's internet connection is able to transfer data

Checking whether an Android device is connected to the internet is straightforward. Sadly, checking whether the device's internet connection is actually working and able to transfer data is not so straightforward. We'll cover both things in this tutorial.

Firstly, here's the method to check whether the device has an internet connection:

boolean isActiveNetworkConnected(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

    return networkInfo != null
        && networkInfo.isAvailable()
        && networkInfo.isConnected();
}

Now, how to check that the internet connection is actually able to transfer data? One way to do this is to ping a web location of your choice, as follows:

boolean isGoogleReachableWithPing() {
    try {
        Runtime runtime = Runtime.getRuntime();
        Process process = runtime.exec("/system/bin/ping -c 1 www.google.com");

        int exitValue = process.waitFor();

        return exitValue == 0;
    } catch (Exception ex) {
        return false;
    }
}

Sadly, the ping command works on some Android devices but not on others (see here for discussion). An alternative approach is to use the InetAddress class, as follows:

boolean isGoogleReachableWithInetAddress() {
    try {
        InetAddress inetAddress = InetAddress.getByName("www.google.com");

        return inetAddress != null && !inetAddress.equals("");
    } catch (Exception ex) {
        return false;
    }
}

Putting all these methods together, what you want is this:

boolean isActiveNetworkConnectedAndWorking(Context context) {
    return isActiveNetworkConnected(context)
        && (isGoogleReachableWithPing() || isGoogleReachableWithInetAddress());
}

You can find all of the above-mentioned methods in the NetworkInspector class in the android-utils repository.