When the Wifi connection is lost, java.io.InputStream does not throw IOException

When the Wifi connection is lost, java.io.InputStream does not throw IOException … here is a solution to the problem.

When the Wifi connection is lost, java.io.InputStream does not throw IOException

I’m having trouble downloading files from URLs for some code in my Android app, here is the code fragment

:

int bytesRead = 0;
final byte[] buffer = new byte[32 * 1024];
InputStream stream = httpUrlConnection.getInputStream();

try {
    while ((bytesRead = stream.read(buffer)) > 0) {
        Log.i("TAG", "Read from steam, Bytes Read: " + bytesRead);
    }
} catch (IOException ex) {
    Recover from lost WIFI connection.
} finally {
    stream.close();
}

If the WiFi connection is lost, my app relies on InputStream.read() to throw IOException. As described in Java 8 documentation, this method should throw IOException “If the input stream is closed, or if other I/O errors occur.” In Android M this happens immediately and my code can handle and recover from exceptions. In Android N, this exception is not thrown, which causes my app to simply get stuck in the read() method, which never breaks. Has anyone else encountered this issue and solved it in a way that doesn’t break backwards compatibility? Is this a new Android N bug?

Solution

If the connection is dropped, reading from the socket can block forever. You need to use a read timeout.

Related Problems and Solutions