Search code examples
androidconnectivityinternet-connection

Android Internet Check (Not Network Check)


So this is quite a revelation - the fact that Android SDK does not seem to have a reliable way to check for internet access.

Allow me to clarify.

Android documentation & most online samples use an approach similar to one found here: https://stackoverflow.com/a/4009133/980917

Something similar to:

public boolean isOnline() {
    ConnectivityManager cm =
        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    return netInfo != null && netInfo.isConnectedOrConnecting();
}

However - this just checks if you are connected to a network and does not guarantee that you can reach the internet.

For those that are not aware of this, its quite easy to reproduce by unplugging the "IN" Ethernet cable from your router or connecting to any Wifi that is not connected to the internet.

KNOWN WORKAROUNDS:

1) Try to reach a web site: https://stackoverflow.com/a/5803489/980917 This is problematic as needs Thread management.

2) Try to ping Google's DNS: https://stackoverflow.com/a/27312494/980917 Does not need to be wrapped in a Thread but will freeze UI.

What I'm looking for:

Ideally I would like to have an internet check as a simple static method in a utility class that can be called from UI or business logic code. Because of this above solutions dont really work well as require additional overhead in the caller class to handle Thread management.

Is there any way to get a reliable internet check in Android w/o polluting the caller class with thread management code ?

Thanks.


Solution

  • I'd made a special class for this with a set of static mehods. It has the well know and shown in your question method to detect if Network is available. It also has a method to check if the target server/host is reachable via this network - checkIsServerReachable(). However since its a networking task it can't be run on UI thread so the only way here is to use AsyncTask, Thread or callback.