Test effective internet connection

Asked

Viewed 1,210 times

5

I have an app where I do a connection test before consulting a webservice, just to display a message to user who has no internet connection. I use a method this way:

public static boolean isConnected(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (null != activeNetwork) {
        return true;
    } else {
        return false;
    }
}

I understood in this question about Testing an application’s Internet connection which is used the Context.CONNECTIVITY_SERVICE, as in my job. Based on some tests I did, this way is done, if it is only connected to WIFI or 4G, It is detected that has a connection, but not always works, because in some cases ends up falling in a INTRANET. It may be an efficient way, but not necessarily as effective.

I saw that answer about Texte de Contexão that it is possible to give a ping in the HOST, but according to the validated answer, not always the hosts accept pings.

I try all this questioning, what would be the most effective way to test if there is an internet connection?

1 answer

4


It’s one thing to have an active network connection(network) another is to be able to access a resource on the Internet.

Checking the existence of an active connection can be done with the code placed in the question.

I would just change

if (null != activeNetwork)

for

if (null != activeNetwork && activeNetwork.isConnected())

will look like this:

public static boolean isConnected(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (null != activeNetwork && activeNetwork.isConnected()) {
        return true;
    } else {
        return false;
    }
}

If this check fails should inform the user of the need of the connection and eventually ask him to turn on the wifi, directing it to the Settings, using

startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));

Checking whether a resource on the Internet is accessible or not depends on the resource itself. So it is not possible to write a method that guarantees 100% that any resource is accessible.
Use ping or check if the google address is accessible only ensures this: that the "pinged" server or Google server is accessible, does not guarantee that your service or any other is.

Thus, as stated, there is no single and effective method of checking the internet connection.
The following approach is to check if there is an active connection and, in each case, the code that accesses the resource, handle the fact that it may not be accessible.

  • 1

    I had forgotten this question! Thank you. = D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.