在Android中等待多个回调 [英] Waiting for multiple callbacks in Android

查看:318
本文介绍了在Android中等待多个回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java线程中,您可以在列表中包含一定数量的线程,将其启动,并具有一个主线程join,然后是另一个主线程,依次执行并等待所有进程完成,然后继续.

In Java threads, you could have some number of threads in a list, start them off, and have a main thread join one, then another, going through and waiting for all processes to complete before moving on.

在其他模型中,我不确定您会怎么做.使用 RootTools 3.0 例如命令类.您创建一个具有三个方法CommandCommand,并且可以在过程结束时使用回调来执行某些操作,但是我不知道您将如何等待多个过程(例如,浏览几个目录并汇总文件大小).

In other models, I'm not sure how you would do that. Take the RootTools 3.0 Command class for example. You create a Command which has three methods, commandOutput, commandFinished, commandTerminated, and while you can use a callback to do something at the end of a process, I don't know how you would wait for multiple processes (For example, going through listing of several directories and summing the file-sizes).

我相信Android Asynctask也会有类似的问题-您可以轻松进行回调,但是无法等待多个任务.除非我想念什么?

I believe the Android Asynctask would have a similar problem - you can easily make a callback, but there is no way to wait for several tasks. Unless I'm missing something?

推荐答案

您可以在正在执行的命令上调用wait().

You can call wait() on the command that you are executing.

尽管在执行此操作之前,您应该关闭您等待的命令的处理程序.您可以通过将RootTools.handlerEnabled设置为false或在每个命令中使用构造函数,然后传入false来禁用该命令的处理程序,来对每个命令执行此操作.

Although before doing this you should turn off the handler for the command that you call wait on. You can do that for every command by setting RootTools.handlerEnabled to false or by using the constructor in each individual command and passing in false to disable the handler for that command.

这很重要,因为如果使用处理程序,它将尝试在您调用wait()的线程上调用回调方法,这将导致死锁.

This is important because if the handler is used then it will try to call the callback methods on the thread that you called wait() and that will result in a deadlock.

当您关闭命令的处理程序并调用wait()时,该命令将在完成后调用notifyAll(),以便您的线程继续运行.

When you turn the handler off for the command and call wait() the command will call notifyAll() when it completed so your thread will resume.

不利的一面是,回调方法将不再在您正在处理的线程中完成,因此除非您实现了处理程序或其他可接受的方法,否则您将无法从这些回调方法中执行任何UI工作解决这个问题的方法.

The negative side of this is that the callback methods will no longer be done in the thread that you are working on so you will not be able to do any UI work from those callback methods unless you implement a handler or some other acceptable solution to deal with this.

这篇关于在Android中等待多个回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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