Android download queue using DownloadManger

Alireza A. Ahmadi picture Alireza A. Ahmadi · Dec 21, 2014 · Viewed 9.4k times · Source

I'm using DownloadManager to download my files in android and its great since it handles everything (connectivity lost, retry, etc.) The problem is I want my file to be downloaded in queue one after another and as far as i know DownloadManager doesn't provide this functionality. So multiple call to DownloadManager.enqueue(...) results in concurrent download of all the files. How can i fix this?

I can not just make a queue in my activity and send downloads to DownloadManger one by one since activity may be destroyed at any time!

Also IntentService doesn't work here!! even though it handles request one by one, call to DownloadManager.enqueue() will run so fast and then the next call and the result would be concurrent download again!

My third option is to use LocalService that gets the request and calls DownloadManager.enqueue() when the previously started download is finished but how should i do it? my service needs to get request form my activity even when its running! (so i can't just put data in intent). To enable communication i need to make it a bound service and as documentations says it destroys when there is nothing bind to it!

bound service runs only as long as another application component is bound to it. 
Multiple components can bind to the service at once, but when all
of them unbind, the service is destroyed.

So i lose my downloads that are in queue when my activity is closed. Am i right?

And there is final option which is using a service in separate process because even if my third option works it only downloads files as long as application is not closed. this option seems to be the scary one since i have to handle interprocess communication and i have no idea what that is!!

So am i missing something?! shouldn't it be an easier solution to my problem?

I just what to download files is queue! I also don't want my service to run indefinitely when there is nothing to download.

Answer

mmlooloo picture mmlooloo · Dec 21, 2014

Very simple:

1)Create a database and insert your url into it.

2)create a receiver for download complete action of downloadmanager in your manifest.

3)when received a download complete read a row from your database and start new download(enqueue).

happy coding:-)