簡體   English   中英

Android:如何等待IntentService for BroadcastReceiver onReceive方法

[英]Android: How to wait IntentService for BroadcastReceiver onReceive method

我有IntentService需要在方法a()中等待BroadcastReceiver()的onReceive()的結果。

現在我使用lmao wait(5000)...所以它不太優雅

IntentService:

private boolean methodA() {

try {
            synchronized (mLocalBroadcastReceiver) {
                mLocalBroadcastReceiver.wait(3000); 
            }
        } catch (InterruptedException e) {
            Log.e(TAG,"error, thread interrupted");
            e.printStackTrace();
        }

if(CONSTANT == true){ 
   return true;
else 
   return false;
}

BroadCastRecievier:

@Override
public void onReceive(Context context, Intent intent) {
    CONSTANT = true //changes somehow between true/false 
}

換句話說:methodA的返回值取決於onReceive()的結果。 如何同步兩個線程?

最后我使用了這樣的線程:

 private void waitForResponse() {
        //wait for response
        thread = new WaitForStatus();
        thread.run();
        try {
            synchronized (thread) {
                thread.wait();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private class WaitForAppStatus implements Runnable {
            @Override
            public void run() {
                while (true) {
                    if (CONSTANT  != -1) {
                        break;
                    } else {
                        try {
                            wait(400);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM