How to check internet access on Android? InetAddress never times out

To check for internet access on Android, you can use the isReachable() method of the InetAddress class. This method attempts to establish a connection to the specified address and returns true if the connection is successful.

However, as you have noted, the isReachable() method may not time out if the connection cannot be established. To work around this issue, you can use the isReachable() method in a separate thread, and set a timeout for the thread using the Thread.sleep() method.

Here's an example of how you can check for internet access on Android using the InetAddress class:

public static boolean isInternetAvailable() {
  try {
    InetAddress ipAddr = InetAddress.getByName("google.com");
    // You can use `ipAddr.isReachable(timeout)` if you want to specify a timeout.
    return ipAddr.isReachable(1000);  // 1000 milliseconds = 1 second
  } catch (IOException e) {
    return false;
  }
}

if (isInternetAvailable()) {
  System.out.println("Internet is available");
} else {
  System.out.println("Internet is not available");
}

I hope this helps! Let me know if you have any questions.