Android: Proper way to download lots of files

独自空忆成欢 提交于 2019-12-24 17:48:00

问题


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?


回答1:


There's no reason to use numerous AsyncTasks, 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
    }
}



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/10661443/android-proper-way-to-download-lots-of-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!