简体   繁体   中英

Check Internet connectivity - 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. 我的手机剂量检测到这种可能性并显示出警报

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM