6

I know this question has been asked a couple of times, example here and here but I`m still not getting the desired results by doing something similar to this when checking for network connectivity

The isAvailable() and isConnected() methods from Network Info both give a result of boolean true when i`m connected to a Wi-Fi router which currently has no internet connectivity .

Here is a screenshot of my phone which can detect the situation in hand. My phone dose detect this possibility and shows a alert for that

Is the only way to make sure that the phone/application is actually connected to the internet is actually poll/ping a resource to check for connectivity or handle an exception when trying to make a request?

Community
  • 1
  • 1
Ashar
  • 119
  • 8
  • Try this solution: http://stackoverflow.com/a/27312494/450534. I have used it in a couple of my apps and it works fine. For me at least. ;-). But give it a go anyway. – Siddharth Lele Dec 26 '15 at 14:04
  • @IceMAN thanks for the reply , so refering to my question "Is the only way to make sure that the phone/application is actually connected to the internet is actually poll/ping a resource to check for connectivity" would be true ? – Ashar Dec 26 '15 at 14:08
  • @Ashar: Yup. That is correct. The solution linked to checks the internet _connectivity_ by pinging the Google DNS 8.8.8.8 – Siddharth Lele Dec 26 '15 at 14:24

1 Answers1

1

As stated by @Levit, Showing two way of checking Network connection / Internet access

-- Ping a Server

// ICMP 
public boolean isOnline() {
    Runtime runtime = Runtime.getRuntime();
    try {
        Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
        int     exitValue = ipProcess.waitFor();
        return (exitValue == 0);
    }
    catch (IOException e)          { e.printStackTrace(); }
    catch (InterruptedException e) { e.printStackTrace(); }

    return false;
}

-- Connect to a Socket on the Internet (advanced)

// TCP/HTTP/DNS (depending on the port, 53=DNS, 80=HTTP, etc.)
public boolean isOnline() {
    try {
        int timeoutMs = 1500;
        Socket sock = new Socket();
        SocketAddress sockaddr = new InetSocketAddress("8.8.8.8", 53);

        sock.connect(sockaddr, timeoutMs);
        sock.close();

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

second method very fast (either way), works on all devices, very reliable. But can't run on the UI thread.

Details here

Majedur
  • 3,074
  • 1
  • 30
  • 43