Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.io.InputStream will not throw IOException when Wifi connectivity is lost

I am running into an issue with some code in my Android application which downloads a file from a URL, here is a code snippet:

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();
}

My application relies on InputStream.read() to throw an IOException if WiFi connectivity is lost. As stated in the Java 8 documentation this method should throw an IOException "if the input stream has been closed, or if some other I/O error occurs". In Android M, this occurs immediately and my code can process and recover from the exception. In Android N, this exception is not thrown which causes my app to simply hang in the read() method, it never breaks out of it. Has anyone else run into this problem and worked around it in such a way that doesn't break backwards compatibility? Is this a new Android N bug?

like image 446
DanMD Avatar asked Jul 18 '26 23:07

DanMD


1 Answers

Reading from a socket can block forever if the connection goes down. You need to use a read timeout.

like image 185
user207421 Avatar answered Jul 20 '26 11:07

user207421



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!