Check Whether Internet Connection is available or not?

前端 未结 3 1545
北恋
北恋 2021-02-06 10:30

I am working on online app. [Problem] when internet is down or not available it gives me error [Force close], I tried to handle using broadCast Receiver but not meet exact solut

3条回答
  •  爱一瞬间的悲伤
    2021-02-06 11:03

    A valid network connection does not necessarily mean you can access the Internet, and the OP was asking for ways to check the availability of an Internet Connection. Some WiFi networks might require users to open a browser and go through some kind of authorization before allowing Internet access, so just checking for a valid WiFi connection is not sufficient in this case.

    A naive approach to checking for raw connectivity without creating a GET/POST connection would be:

    private boolean isConnected() {
    
        try {
            InetAddress.getByName("google.com");
        } catch (UnknownHostException e) {
            return false;
        }
        return true;
    }
    

    WARNING1: Having done some testing I must warn that the code above DOES NOT REALLY WORK even if it appears so the first couple of times.

    The code attempts to resolve a host name that is not already in the DNS cache, so once a successful lookup has been cached the code will continue returning true even if the host is not reachable anymore since all modern OS's do DNS caching.

    BUT... On Android the InetAddress class has an additional method that is not found in the standard JavaSE - InetAddress.isReachable (int timeout) which according to javadocs:

    "Tries to reach this InetAddress. This method first tries to use ICMP (ICMP ECHO REQUEST), falling back to a TCP connection on port 7 (Echo) of the remote host."

    So a possible fix to the code above would be

    InetAddress.getByName("google.com").isReachable(5000);
    

    In cases when ICMP packets are blocked the only reliable way to check reachability would be to create a real connection to your host either via URLConnection, HttpClient, Socket or anything in between.

提交回复
热议问题