I'm using an HttpURLConnection to fetch a bitmap from a specified URL using the method as described here, the code for which is copied below for convenience:
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
// Log exception
return null;
}
}
I need the whole fetch and decode process to finish within a specific time, because I'm running it from a BroadcastReceiver (albeit within an AsyncTask to keep it off the UI thread). Therefore the whole receiver operation must be finished within 10 seconds to avoid being killed mid-way, so I want to allow the bitmap fetch and decode, say, 5 seconds.
I suppose that I'll be advised not to attempt it this way, and instead use an IntentService or something, but nonetheless I wonder whether it's possible to avoid that just by ensuring the AsyncTask fetch is completed quickly (even if that is by way of a timeout).
I'm aware that I can set the following timeouts on connection
:
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
But my understanding is that the connect timeout just puts a limit on how long it takes to connect, while the read timeout does so in respect of how long it takes to start reading the data.
But, neither of these puts a limit on the whole process: connect, read, decode.
I guess part of my uncertainty is over when the data is actually read... is it when you call connection.connect()
or is it when you call connection.getInputStream()
or is it only when you call BitmapFactory.decodeStream(input)
?
If the data is only read when you call decodeStream()
then how do you put a timeout on that?
Maybe I need to set an overarching timer, and close things down gracefully when that fires, rather than trying to rely on an HttpURLConnection-related timeout?