[英]Android / Java waiting for handler before returning inside of Service
我需要使用一个现有的API,该API假定它将直接在Activity中的简单应用程序中使用。 我的用例需要从服务中调用API,然后等待所需的处理程序返回所需的数据。
我尝试了许多Java并发选项,但均未成功。 谁能建议一个更好的方法?
下面是一个大大简化的示例,比工作示例更多的是伪代码。
public class dataConnection {
Controlx xControl;
CountDownLatch doneSignal = new CountDownLatch(1);
Context c = null;
private String data1;
Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
setReturnData(msg);
doneSignal.countDown();
}
};
public dataConnection(Context ctx) {
this.c = ctx;
xControl = new Controlx (c, mHandler);
}
private void setReturnData(int rc) {
this.rc = rc;
}
private int getReturnData() {
return this.rc;
}
public int getRealData() {
//API will timeout in 10 seconds if data is not retrieved before that
xControl.dataCmd(10);
//Wait here for handler to finish and then retrieve data to return
doneSignal.await();
int i = getReturnData();
Log.v("log_tag", "RETURN NOW!!!!!!!!!!!!!!!");
return data;
}
如果Handler
使用与getRealData()
方法相同的线程, getRealData()
防止其看到Message
。 Looper
必须先完成一件事,然后才能处理任何新事物。
如果为处理程序创建新的线程和循环程序,它将允许它们分别运行。 根据您的需求,也可以使用Future<Integer>
对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.