Effective internet connection test

5

I have an application in which I test a connection before consulting a webservice , to display a message to a user who does not have an internet connection. I use a method like this:

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 noticed in this question about Test internet connection of an application which is used Context.CONNECTIVITY_SERVICE , as in my function. Based on some tests I did, this way it is done, if it is only connected to the WIFI or 4G, it is detected that it has a connection, but it does not always work, because in some cases it ends up falling into an INTRANET . It may be an efficient, but not necessarily as effective, way.

I've seen this answer about Context Texts that you can give < in HOST , but according to the validated response, hosts do not always accept pings in>.

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

    
asked by anonymous 09.04.2017 / 01:36

1 answer

4

It's one thing to have an active connection to the network (network), and another is accessing an internet resource.

Verifying the existence of an active connection can be made with the code placed in the question.

I just changed

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, you should inform the user of the need for the connection and possibly ask him to connect the wifi by directing it to the Settings , using

startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));

Whether or not an internet resource is accessible depends on the resource itself. Therefore it is not possible to write a method that guarantees 100% that any resource is accessible. Using ping or checking that the google address is accessible only ensures that the "pingado" server or Google server is accessible, it does not guarantee that your service or any other service is available. p>

So, in terms of which it refers, there is no single, effective method of verifying your internet connection. The next approach is to check for an active connection and, in each case, the code that accesses the feature, deal with the fact that it may not be accessible.

    
09.04.2017 / 13:31