Reputation: 6181
In my app I need to download a bunch of files. My original plan was use an individual AsyncTask for each file, so that I can notify the rest of the app when each file is downloaded. I found it testing that while this works, its seems really memory in-efficient. Is there a good way to use a single AsyncTask or maybe a Service to download the files and notify on each files complete?
Upvotes: 1
Views: 825
Reputation: 23508
There's no reason to use numerous AsyncTask
s, since you may create the list of file names, pass it to the single AsyncTask
, and after each file is downloaded, publish the download progress with publishProgress()
and onProgressUpdate()
, which is run in UI thread and can easily notify other activities in your application.
private class DownloadFilesTask extends AsyncTask<URL, String, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
for (int i = 0; i < count; i++) {
Downloader.downloadFile(urls[i]);
publishProgress(urls[i].toString());
}
return 0;
}
protected void onProgressUpdate(String... progress) {
// notify whomever you like with url from progress[0]
// this is run on UI thread
}
protected void onPostExecute(Long result) {
// do something else
// this is also run on UI thread
}
}
Upvotes: 1
Reputation: 2435
From memory and network standpoint you would be better off using just one AsyncTask (or a Java thread) and download all files one by one. This greatly improves device's responsiveness and also consumes a little of memory. In case you can control server side, I would also suggest you zip smaller files to one archive (my project also downloads a lot of files via HTTP) and it shows great improvement of speed if files are combined into archives with size of about 2-4 MB and downloaded. In case you are downloading using just TCP/IP connection, it will not matter how big are files if you will not reestablish connection every time. But again for HTTP the biggest time waster is usually connection establishment.
Upvotes: 0
Reputation: 41858
A remote service would work, but I think it is the wrong approach since you have just a limited functionality for it.
I would use AsyncTask, but have it called by a method.
When you are finished in the AsyncTask then call the method again that will create a new AsyncTask after removing the item in the list, or updating some counter.
Remember that an AsyncTask cannot be reused, so it needs to be created fresh each time.
Upvotes: 0