Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Download Multiple Files and show progress in ListView

I have N files to download. I want to download them serially in background - one after other. I want to show the progress and status in a ListView. So, ListView looks like:

File1 ...downloaded

File2....downloaded

File3... in Progress say 39%

File4... Pending

....

Listview refreshed periodically (say every 2 seconds) and files are large: 50 MB or so. So they take 1 minute plus to download.

I will pass a list of File URLs to the AsyncTask and have it downloaded in background. Question is how do you feed progress back into ListView.

Consider that user may navigate away from ListView page leaving AsyncTask running only to come back to see the status of download.

So how does the ListView "observe" the progress of AsyncTask and display it ?

I am thinking adding a set of static variables AsyncTask (protecting them with "Synchronized" blocks) and the use a periodic UI Updater inside Fragment that displays the ListView. So the fragment will have something like this:

Repeat a task with a time delay?

Is there a design pattern, public project or sample code for this ?

Sorry, I don't ave a good picture. Closest thing to what I am describing is here (Similar but I plan to use AsyncTask and serial download):

Picture

like image 602
user1667302 Avatar asked Sep 14 '13 00:09

user1667302


2 Answers

Follow these steps

  1. create a service with asyncTask in it for downloading file
  2. start the task in onStartCommand of service
  3. Register a broadcast reciever in your activity to recieve progress from service
  4. onProgressUpdate of AsyncTask send broadcast to your activiy
  5. display the progress in the ListView
like image 161
Rajesh Batth Avatar answered Oct 20 '22 20:10

Rajesh Batth


When starting download you can use the reference of progress-bar and update it using a handler.

Asynctask would not be a good idea for you. You should read this before jump deep with Asynctask.

For long lasting background operation you should look into Service. [IntentService] is a good candidate for this as its uses queue to keep track of multiple request. Boundservice this case good option.

Alternatively if you want more control on thread pool and on execution you can think of writing your own downloader using a blocking queue and Executor, where you will be able to control number of thread and queue size

like image 43
minhaz Avatar answered Oct 20 '22 20:10

minhaz