How do I download multiple files in a queue one by one! I\'m using this as a sample code, since. I would be passing the URLs to download in Strings from my local DB dynamic
A good way of queuing up requests to be handled asynchronously, one at a time, is with an IntentService
. If you have an IntentService
which reads URLs from the supplied Intent
, then all you have to do is create an Intent
for each file you want to download, and send each Intent
to the service,
Here is a good tutorial.
EDIT: I see you've already referred to a similar question, where the answer recommends IntentService
. So, maybe you should use an IntentService
. :)
From API 11 up, a good approach is to use a FixedThreadPool with async tasks. Do once:
ExecutorService threadPoolExecutor = Executors.newFixedThreadPool(3);
Where 3 is the number of downloads you want to run at the same time. It will queueu the task if there are already 3 downloads running, and automatically handle the task later. Launch your async tasks with:
yourAsynTask.executeOnExecutor(threadPoolExecutor, params);
Params is probably the url you wish to connect to. You can read it out in the onPostExecute of your asynctask, and connect to the server using a HttpURLConnection.
Make sure you call down this on shutdown:
threadPoolExecutor.shutdown()
What's the best way to implement a download queue in Android?
Use an IntentService
. It supplies the queue and the background thread for you, so all you have to do is put your download logic in onHandleIntent()
. See here for a sample project demonstrating this.