簡體   English   中英

如何暫停服務並等待其他服務完成

[英]How to pause Service and wait till other service is finished

我創建了一個服務TimingService 服務

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回調做到這onRecive

在TimingService中動態創建廣播接收器,並通過本地廣播管理器為適當的事件注冊它。 在您的其他服務中,通過“本地廣播管理器”引發事件。

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

我意識到您正在用Java編寫,但是可以使用C#的一種方法是通過ManualResetEvent,它是一個類,它允許一個線程等待直到另一個線程“對其發出信號”。 您可以嘗試使用Java類似的方法。 (很抱歉,我並沒有在最后一點上更具體,我通常使用C#/ Xamarin編寫我的Android應用程序)。

暫無
暫無

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

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