简体   繁体   English

如何在同一线程中等待onReceive完成?

[英]How to wait for onReceive to finish while in same thread?

I have a BroadcastReceiver registered in the UI thread that grabs some information from the Bundle in its onReceive method. 我在UI线程中注册了一个BroadcastReceiver,它通过其onReceive方法从Bundle中获取一些信息。 I need these values before I proceed in my main thread. 在进入主线程之前,我需要这些值。

Is there any way to wait for the onReceive to finish before trying to use those values? 在尝试使用这些值之前,有什么方法可以等待onReceive完成吗? I am running into timing issues where onReceive sets the values AFTER I try to use them. 我遇到了时序问题,在尝试使用onReceive设置这些值之后,就开始使用它们。 Having the thread sleep doesn't work, since they're on the same thread. 使线程处于休眠状态是行不通的,因为它们处于同一线程中。

Would it make sense to register the receiver in an AsyncTask, and call wait() on the main thread, then have onReceive notify() once it completes? 在AsyncTask中注册接收器,并在主线程上调用wait(),然后在完成后让onReceive notify()有意义吗?

String a = "hi";
IntentFilter filter = new IntentFilter();
filter.addAction(MY_CUSTOM_INTENT);
BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // Set the variable values here
        a = "bye";
    }
};
getApplicationContext().registerReceiver(receiver, filter);

// Get the values, I am getting a = "hi" here because the onReceive code has 
// not been reached yet
// How can I guarantee that a = "bye" from this method?
getA();

where method is something like 方法在哪里像

String getA() {
    return a;
}

You seem to be over-complicating things. 您似乎使事情变得过于复杂。 It's hard to know what you're really after based on the example code, but the code that comes after registerReceiver() should just do whatever else it needs to do and then return, without waiting for or hoping for the Broadcast to have been received. 根据示例代码很难知道您真正想要的是什么,但是registerReceiver()之后的代码应该做其他需要做的事情然后返回,而不用等待或希望已收到广播。 。 onReceive() should include whatever code you want to have executed at that point (which may well just be a method call, eg updateA("bye") . onReceive()应该包括您当时想要执行的任何代码(很可能只是方法调用,例如updateA("bye")

好吧,如果您打算以任何一种方式阻塞主线程,那么最好也做得很优雅。用AsyncTask注册接收器,并使用Dialog让用户知道您在做什么或正在装载什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM