【问题标题】:Parallel downloading and get individual download progress via AsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)通过 AsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR) 并行下载并获取单独的下载进度
【发布时间】:2019-12-05 16:28:08
【问题描述】:

我正在使用并行下载文件

asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)

我想要我添加的每个任务的个人进度。

ArrayList<AsyncTask> mListAsync = new ArrayList<>();
final DownloadTask downloadTask = new DownloadTask(mContext, name);
downloadTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,mVideoUrl.trim());
mListAsync.add(downloadTask );

以上是我用来下载文件的示例代码,我确实维护了一个数组列表来获取队列中添加了多少任务。

有什么方法可以让我在线程池中添加单个 AsyncTask 进度更新。

【问题讨论】:

    标签: android android-asynctask threadpoolexecutor


    【解决方案1】:

    假设您的 DownloadTask 类使用https://developer.android.com/reference/android/os/AsyncTask.html#publishProgress(Progress...) 方法,您可以在来自https://developer.android.com/reference/android/os/AsyncTask.html#onProgressUpdate(Progress...) 的回调中获取当前进度

    编辑: 一些带有回调的示例代码:

    public class SampleTask extends AsyncTask<Void, Integer, String> {
    
        private final int id;
        private final ProgressCallback callback;
    
        public SampleTask(int uniqueId, ProgressCallback callback){
            this.id = uniqueId;
            this.callback = callback;
        }
    
        @Override
        protected String doInBackground(Void... voids) {
            // do work and call publish progress in here
            for(int i = 0; i <= 100; i++) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e){
                    e.printStackTrace();
                }
                publishProgress(i);
            }
            return null;
        }
    
        @Override
        protected void onProgressUpdate(Integer... values) {
            //handle progress updates from in here
            callback.onProgress(id, values[0]);
        }
    }
    
    public interface ProgressCallback{
        void onProgress(int uniqueId, int progress);
    }
    

    【讨论】:

    • 问题是它可以为单个异步完成。如果我使用asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR) 怎么办?如何获得每个异步调用的单独进度?
    • 我不太明白你的意思。每个 AsyncTask 将提交给 AsyncTask.THREAD_POOL_EXECUTOR 定义的执行器。当它们被执行时,publishProgress 将更新正在运行的 AsyncTask 的进度。如果您询问如何在执行时区分 AsyncTasks,您可以在创建时为 DownloadTask 设置另一个参数以帮助区分它。这可以像一个唯一的 int 一样简单,甚至可以是一个在给出进度时处理的回调。
    • 用一个例子编辑了我的答案
    • 明白了!!谢谢:)
    猜你喜欢
    • 1970-01-01
    • 2013-08-21
    • 2014-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多