Sunday, 27 September 2015

Android: how to check that internet connection is able to transfer data

Checking whether an Android device is connected to the internet is straightforward. Checking whether the device's internet connection is actually working and able to upload/download data unfortunately 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;
    }
}

The method above is ideal but unfortunately the ping command works on some Android devices and not on others (see here). An alternative way to check that the internet connection is able to transfer data is 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());
}

UPDATE: These methods are now contained in the NetworkInspector class in the following repository:
https://bitbucket.org/adilson05uk/utils-library

No comments: