سؤال

I try to download a file from a mobile device. The mobile is connected by wifi, and sometimes, the mobile change of location, and so connect to another wifi. For the download, I use :

    final URLConnection ucon = url.openConnection();
    ucon.setReadTimeout(10000);
    ucon.setConnectTimeout(10000);
    final InputStream inputStream = ucon.getInputStream();
    final BufferedInputStream bis = new BufferedInputStream(inputStream);

And after bis.available() and bis.read() to get data until byte count > ucon.getContentLength().

I expected an (IO)Exception (or a TimeoutException at least) when the wifi connection changes, but nothing.

In an other class, I check the Network connection (with a BroadcastReceiver), and I see the events disconnect/connect normally.So, I can use the broadcast receiver to stop and restart the download, but I think it's not the best way to do that.

Have you any idea to get an Exception in this case ?

Thank you.

هل كانت مفيدة؟

المحلول

I believe it might not be possible to get an exception/error in this case, at least not reliably.

The peer is basically not available, so you won't receive any data anymore. If you won't send data (which does not happen if you use a HTTP download), nothing will ever happen as long as you don't implement your own timeout.

So I would go for your way of listening for network change events.

Further note:

The problem is, for a TCP connection, you (or the OS) can only detect errors:

  • if you send data and there is not ACK coming back from the other side
  • if the other side sends a RST or something similar.

If the other side is gone (or unreachable, in your case) and you don't send data, you can therefore not detect an error (only via your own timeout).

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top