如何暂停服务并等待其他服务完成

时间:2016-08-04 18:00:08

标签: android

我创建了一个Service 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,此intent通过ResponseReciver报告状态。

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

1 个答案:

答案 0 :(得分:0)

在TimingService中动态创建广播接收器,并通过本地广播管理器为相应的事件注册它。在您的其他服务中,通过本地广播管理器提升活动。

另一种方法是使用某种锁定策略(例如,通过Mutex)。

我意识到你正在用Java编写,但在C#中,你可以通过一个方法来实现这一点,这是一个允许一个线程等到另一个线程&#34;信号&#34;它。你可以在Java中尝试类似的东西。 (对不起,关于最后一点不具体,我通常用C#/ Xamarin编写我的Android应用程序。)