How to restart Service using IntentService in andr

2019-03-05 07:50发布

问题:

I am able to stop my ServiceA(it is started using AlarmManager) when an IntentService is running by sending a broadcast from IntentService to broadcast receiver. I want to Start the same ServiceA again after my IntentService finished his work.

Ex-I have Service SrvA,IntentService IntSrvB and BroadcastReceiver MyBcr.When my IntSrvB running i am able to stop SrvA.My problem is How to Restart SrvA again when my IntSrvB finish his work.

Note-ServA is started using AlarmManager.

回答1:

EDIT: Based on your code, you can pass your variables myIntent & myIntent2 into your IntentService class - you can then use them to recreate exact replicas of the pending intents used with the AlarmManager.

Please note that it looks like you set an Alarm for each intent that repeats once "NOW" and then at intervals after that. You then implicitly start the service again i.e. you start the service twice "NOW". That looks like a mistake - look at the docs for the AlarmManager.setRepeating() method.


Original answer below...

Put this into your IntentService:

@Override
protected void onHandleIntent(Intent intent)
{
    try
    {
        // STOP SERVICE

        // DO YOUR WORK HERE
    }
    finally
    {
        // START SERVICE
    }

}

You already have the code to stop the service. You can take the "start service" code from your BroadcastReceiver and put it in the finally block.

I would not recommend overriding onDestroy() in general on Android.

NOTE: I don't think this is the best way to design your app, but I'm answering your question. Personally, I would have a method in my main Service that is able to disable & enable its functionality - and then call that method instead of starting & stopping the service.