2016-08-04 69 views
0

我創建了一個服務TimingService Service如何暫停服務,等到其他服務完成

public class TimingService extends Service { 

包含的ServiceHandler

// Handler that receives messages from the thread 
private final class ServiceHandler extends Handler { 
    public ServiceHandler(Looper looper) { 
     super(looper); 
    } 

    @Override 
    public void handleMessage(Message msg) { 
     // Normally we would do some work here, like download a file. 
     // For our sample, we just sleep for 5 seconds. 
     try { 
      for(int i = 0; i<3; i++){ 
       Intent intentDirty = new Intent(TimingService.this, DirtyJobService.class); 
       startService(intentDirty); 
       // Instantiates a new DownloadStateReceiver 
       ResponseReceiver mDownloadStateReceiver = new ResponseReceiver(); 

       IntentFilter mStatusIntentFilter = new IntentFilter(DirtyJobService.Constants.BROADCAST_ACTION); 
       mStatusIntentFilter.addCategory(Intent.CATEGORY_DEFAULT); 


       // Registers the DownloadStateReceiver and its intent filters 
       LocalBroadcastManager.getInstance(TimingService.this).registerReceiver(mDownloadStateReceiver, mStatusIntentFilter); 



      } 

     } catch (InterruptedException e) { 
      // Restore interrupt status. 
      Thread.currentThread().interrupt(); 
     } 
     // Stop the service using the startId, so that we don't stop 
     // the service in the middle of handling another job 
     stopSelf(msg.arg1); 
    } 
} 

// Broadcast receiver for receiving status updates from the IntentService 
private class ResponseReceiver extends BroadcastReceiver { 
    // Prevents instantiation 
    // private DownloadStateReceiver() { 
    // } 
    // Called when the BroadcastReceiver gets an Intent it's registered to receive 
    @Override 
    public void onReceive(Context context, Intent intent) { 

    } 
} 

TimingService觸發intentDirty這個意向報告與ResponseReciver狀態。

現在我想暫停void handleMessage(Message msg)及其for(int i = 0; i<3; i++),直到intentDirty完成。如何通過BroadcastReciver和onRecive回調?

回答

0

在TimingService中動態創建廣播接收器,並通過本地廣播管理器註冊適當的事件。在您的其他服務中,通過本地廣播管理器提出事件。

另一種方法是使用某種鎖定策略(例如,通過互斥鎖)。

我意識到你正在用Java編寫,但在C#中,你可以通過一種方法來實現這一點,就是通過一個ManualResetEvent,它允許一個線程等待另一個線程「發送」它。你可以在Java中嘗試類似的東西。 (對不起,關於最後一點不是更具體,我通常在C#/ Xamarin中編寫我的Android應用程序)。