Android
Internet Connectivity
Mobile Development
Network Troubleshooting
InetAddress

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

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Checking for internet access on an Android device is crucial for applications that rely on network operations. Relying merely on checking whether a device is connected to a network does not guarantee internet access, as the network may not provide an actual internet connection. This is key in distinguishing between having a connected Wi-Fi or mobile data link, and actually being able to reach the outside world through that link.

Using InetAddress

A common method for checking internet connectivity is attempting to reach a known server by using InetAddress. The typical process involves using InetAddress.getByName() to resolve a hostname to an IP address, which can indicate whether the internet is accessible. However, developers often face an issue with this method: it tends not to timeout, even if the internet is not reachable, leading to a stalled application.

Why InetAddress Might Not Timeout

InetAddress.getByName() does not have native timeout handling. It relies entirely on the underlying network stack of the operating system, which can lead to indeterminate behavior when a network is congested or when the internet is not accessible. In Android, this can cause the app to appear unresponsive if proper asynchronous handling isn't implemented.

Implementing a Reliable Check

A more effective way to check for internet connectivity involves:

  1. Using HttpURLConnection or OkHttpClient to attempt fetching data from a reliable endpoint.
  2. Setting explicit timeouts on the network request.
  3. Handling exceptions properly to differentiate between different issues (e.g., no internet, timeout, server down).

Here’s how you can implement this approach:

java
1public boolean hasInternetAccess() {
2    try {
3        HttpURLConnection urlc = (HttpURLConnection) 
4            (new URL("http://clients3.google.com/generate_204")
5            .openConnection());
6        urlc.setRequestProperty("User-Agent", "Android");
7        urlc.setRequestProperty("Connection", "close");
8        urlc.setConnectTimeout(1500);
9        urlc.connect();
10        return (urlc.getResponseCode() == 204 && urlc.getContentLength() == 0);
11    } catch (IOException e) {
12        Log.e("Internet Check", "Error checking internet connection", e);
13    }
14    return false;
15}

This code attempts to connect to a Google server that always returns HTTP 204 for every request, making it a reliable endpoint to check internet accessibility. The connection timeout is set to 1500 milliseconds, which is typically adequate to determine if the network latency is acceptable.

Table: Comparison of Methods

MethodTimeout SupportReliabilityComplexity
InetAddress.getByName()NoLowLow
HttpURLConnection with Known URLYesHighMedium

Handling Network State Changes

It’s important also to monitor changes in network state and adjust your checks accordingly. Android apps can listen for changes in network connectivity through BroadcastReceiver listening for ConnectivityManager.CONNECTIVITY_ACTION broadcasts. This way, your app can respond immediately to changes in network availability.

Async Handling

Given the blocking nature of network operations, it's crucial to run these checks in a background thread or an asynchronous task. This ensures that the UI remains responsive and you provide the best user experience.

Testing and Validation

Lastly, rigorously test your approach under various network conditions. Use tools like Charles or Wireshark to simulate different network environments and ensure your app gracefully handles all possible states.

In summary, checking internet access effectively requires more than just checking if a device is connected to a network. By implementing a solid connection check using HttpURLConnection, handling exceptions and changes in network state, and ensuring operations are performed off the main UI thread, apps can offer a more reliable and smooth user experience.


Course illustration
Course illustration

All Rights Reserved.