Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check Internet connectivity - Android

Tags:

android

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?

like image 760
Ashar Avatar asked Dec 26 '15 11:12

Ashar


1 Answers

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

like image 99
Majedur Avatar answered Sep 30 '22 18:09

Majedur