繁体   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