安卓:正确的方式来下载大量文件 [英] Android: Proper way to download lots of files

查看:127
本文介绍了安卓:正确的方式来下载大量文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用我需要下载一堆文件。我原来的计划是使用一个单独的AsyncTask为每个文件,这样当每个文件下载我可以通知应用程序的其余部分。我发现它的测试,虽然这个工程,它似乎真的在高效的内存。有没有办法使用单一的AsyncTask或者服务下载的文件,并通知每个文件的一个很好的方式完成?

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?

推荐答案

有没有理由使用众多的的AsyncTask S,因为您可以创建文件名列表,通它的单的AsyncTask ,每个文件下载后,发布与下载进度publishProgress() onProgressUpdate(),这是在UI线程中运行,并可以很容易地通知应用程序中的其他活动。

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
    }
}

这篇关于安卓:正确的方式来下载大量文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆