栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

等待多个AsyncTask完成

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

等待多个AsyncTask完成

您还可以简单地将共享库中的计数器递减作为的一部分

onPostExecute
。由于
onPostExecute
在同一线程(主线程)上运行,因此您不必担心同步。

更新1

共享对象可能看起来像这样:

public class WorkCounter {    private int runningTasks;    private final Context ctx;    public WorkCounter(int numberOfTasks, Context ctx) {        this.runningTasks = numberOfTasks;        this.ctx = ctx;    }    // only call this in onPostExecute! (or add synchronized to method declaration)    public void taskFinished() {        if (--runningTasks == 0) { LocalBroadcastManager mgr = LocalBroadcastManager.getInstance(this.ctx); mgr.sendBroadcast(new Intent("all_tasks_have_finished"));        }    }}

更新2

根据对此答案的评论,OP正在寻找一种可以避免建立新课程的解决方案。这可以通过

AtomicInteger
在生成的
AsyncTask
s中共享一个来完成:

// TODO Update type params according to your needs.public class MyAsyncTask extends AsyncTask<Void,Void,Void> {    // This instance should be created before creating your async tasks.    // Its start count should be equal to the number of async tasks that you will spawn.    // It is important that the same AtomicInteger is supplied to all the spawned async tasks such that they share the same work counter.    private final AtomicInteger workCounter;    public MyAsyncTask(AtomicInteger workCounter) {        this.workCounter = workCounter;    }    // TODO implement doInBackground    @Override    public void onPostExecute(Void result) {        // Job is done, decrement the work counter.        int tasksLeft = this.workCounter.decrementAndGet();        // If the count has reached zero, all async tasks have finished.        if (tasksLeft == 0) { // Make activity aware by sending a broadcast. LocalBroadcastManager mgr = LocalBroadcastManager.getInstance(this.ctx); mgr.sendBroadcast(new Intent("all_tasks_have_finished")); }    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/419302.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号