我有一个绑定(bind)服务,我向该服务发送消息,它也将消息发回。所有这些都发生在一个不同的类中,称为DataItems。
主要 Activity 使用此方法调用 DataItems:
DataItems.getItems();
DataItems 将向请求项目的服务发送一条消息,当它收到返回的消息时(通过处理程序,它应该将其发送回调用 Activity )。
Items results = null;
public Items getItems() {
sendMessage(); // sends a message to service;
boolean messageNotReceived = true;
--> while(messageNotReceived); // wait for message to come back;
return results;
}
private class CustomHandler extends Handler {
@Override
public void handleMessage(Message msg) {
results = msg.getData().getParcelable("items");
messageNotReceived = true;
}
}
问题在于while循环会阻塞线程,直到while循环完成后,handleMessage方法才会被调用。我认为其中一个必须在单独的线程中运行,以便保持另一个畅通无阻。
如果我在单独的线程中运行 getItems(),它将如何将结果返回给调用 Activity ?
getItems() {
new Thread(new Runnable() {
@Override
public void run() {
while(messageNotReceived);
// how to return value from here???
}
}
// any operation here will continue in parallel with the thread
// so any return statements here will be returned to the activity.
}
那么问题是如何在不阻塞整个执行线程的情况下等待来自Service的消息?
最佳答案
在这种情况下,我建议您在 Activity
中使用 BroadcastReceiver
。每当 handleMessage
完成时,将 Broadcast
发送到您的 Activity
,然后您可以调用 DataItems.getItems();
关于android - 使用线程等待来自服务的消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24682517/