user557240
user557240

Reputation: 273

Android Best way to use AsyncTask

I've been looking at this guide:

http://developer.android.com/training/basics/network-ops/connecting.html

And was wondering what would be the best way to download multiple files. First I need to download a text file from a url to determine which files to download.

Should I have 2 separate ASyncTasks, one to download the file and then the other to download the remaining files? Otherwise my code which depends on the first file crashes since the Async task does not complete in time.

Also for the progress dialogue should I make a new one for each file or try to update the previous one?

Thanks

Orginally I was creating a new AsyncTask for each file to download.

Upvotes: 0

Views: 363

Answers (2)

Joe Malin
Joe Malin

Reputation: 8641

In general, if you want the files to remain on the devices, and you're downloading multiple files based on the results of downloading one file, then you should

  1. Use an IntentService to download and store/parse the first file.
  2. Use an IntentService to read the results of the first download and then download the remaining files. If you need to, you can use a progress bar notification in the notification area. Meanwhile, the user can continue working in the app or even switch to another app and the download will continue.

An IntentService is immune to Activity lifecycle changes that might kill an AsyncTask.

Any time you download data, persist it somewhere. You can always check to see if the data is outdated. On the other hand, if there's no connectivity, users have the last "good" data.

To learn more about IntentService, see Running in a Background Service. The content provider in the sample app illustrates downloading "metadata" for other files. The sample also demonstrates how to check for connectivity before downloading.

Upvotes: 2

Sam
Sam

Reputation: 86958

There is no perfect answer to cover every situation possible.

  • If you are happy with one quick running AsyncTask, don't change anything.
  • If you are using API 9+, you could switch to the DownloadManager class and let it workout the particulars.

If you need references, Download a file with Android, and showing the progress in a ProgressDialog, provides examples for multiple ways to download a file with an active ProgressBar.

Upvotes: 1

Related Questions