Detect if Android device has Internet connection

后端 未结 15 2665
野性不改
野性不改 2020-11-22 08:54

I need to tell if my device has Internet connection or not. I found many answers like:

private boolean isNetworkAvailable() {
    ConnectivityManager connect         


        
15条回答
  •  一整个雨季
    2020-11-22 09:48

    You don't necessarily need to make a full HTTP connection. You could try just opening a TCP connection to a known host and if it succeeds you have internet connectivity.

    public boolean hostAvailable(String host, int port) {
      try (Socket socket = new Socket()) {
        socket.connect(new InetSocketAddress(host, port), 2000);
        return true;
      } catch (IOException e) {
        // Either we have a timeout or unreachable host or failed DNS lookup
        System.out.println(e);
        return false;
      }
    }
    

    Then just check with:

    boolean online = hostAvailable("www.google.com", 80);
    

提交回复
热议问题