dephinera
dephinera

Reputation: 3770

Android is device connected to the internet method

I want to create a method which tells if the device is online. As far as I understand ConnectivityManager tells only if the device is connected to a network. This doesn't mean that the device is connected to the internet. To ensure that the device is online I'm using InetAddress.getByName("google.com").isReachable(3); but I can't use it on the main thread. I can create a separate thread to check the connectivity and then use a callback function but is there another way? I don't want my app to do anything before it is connected. Do you have any solutions? Thank you!

Upvotes: 1

Views: 274

Answers (2)

FunkTheMonk
FunkTheMonk

Reputation: 10938

With any networking, there isn't a guaranteed way to check whether or not you are connected to an endpoint without actually sending data. Even if the device is connected to a network, has an ip address, recently received data, e.t.c, it doesn't mean that you still have a connection.

I would suggest allowing the user to progress into your application as much as possible, queuing up the requests to your server in the background whilst a connection is established. Use the same framework to resend data if the connection is lost whilst the user is using the app. Make the connection to the server as transparent to the user as possible, unless it fails to connect after ~1 minute

Upvotes: 1

Bronx
Bronx

Reputation: 4510

try this:

public static boolean isOnline(Context context) {

    ConnectivityManager cm =
            (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo netInfo = cm.getActiveNetworkInfo();

    if (netInfo != null && netInfo.isConnected()) {
        return true;
    }

    return false;
}

Upvotes: 1

Related Questions