Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Internet connectivity check better method

According to the Android developer site, Determining and Monitoring the Connectivity Status, we can check there is an active Internet connection. But this is not working if even only Wi-Fi is connected and not Internet available (it notifies there is an Internet connection).

Now I ping a website and check whether Internet connections are available or not. And this method needs some more processing time. Is there a better method for checking Internet connectivity than this to avoid the time delay in ping the address?

like image 672
Rohith Krishnan Avatar asked Jul 05 '17 06:07

Rohith Krishnan


Video Answer


1 Answers

Try this:

It's really simple and fast:

public boolean isInternetAvailable(String address, int port, int timeoutMs) {
    try {
        Socket sock = new Socket();
        SocketAddress sockaddr = new InetSocketAddress(address, port);

        sock.connect(sockaddr, timeoutMs); // This will block no more than timeoutMs
        sock.close();

        return true;

    } catch (IOException e) { return false; }
}

Then wherever you want to check just use this:

if (isInternetAvailable("8.8.8.8", 53, 1000)) {
     // Internet available, do something
} else {
     // Internet not available
}
like image 123
sumit Avatar answered Sep 27 '22 22:09

sumit