1

我有IntentService需要在方法a()中等待BroadcastReceiver()的onReceive()的结果。Android:如何等待IntentService for BroadcastReceiver onReceive方法

现在我使用LMAO的等待(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()的结果。如何同步两个线程?

+0

调用了methodA( –

+0

通过读取IntentService文档开始,因为这不是它是什么 –

+0

@TimCastelijns我IntentService做更多的人卸载任务,而不仅仅是methodA(),methodA()是小部分 – oginski

回答

0

最后我使用线程这样的:)的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(); 
         } 
        } 
       } 
      } 
     } 
相关问题