Cilenco
Cilenco

Reputation: 7117

Prevent Service to restart

I have an IntentService which is started from a BroadcastReceiver with startService(service). When I get new informations in the BroadcastReceiver the new infos are pushed through an intent with startService(service) again to the IntentService but then the service is restarted. Can I prevent this? I want to push new informations to the IntentService without restating it.

Upvotes: 0

Views: 458

Answers (2)

fedepaol
fedepaol

Reputation: 6862

Intent service are intended to be started with an intent, execute their job and finish. They are more like an asynctask from this point of view. This is the reason why your intentservice is restarting.

onHandleIntent should do some work and finish. You could do some tricks to make it blocking but that would go against the nature of intent services.

What you should do is to have a classic Service. If you are getting ANR errors, you should perform all the time intensive operations inside a thread or an asynctask hosted inside the service itself.

Upvotes: 1

chalup
chalup

Reputation: 8516

I assume you need to share some state for handling subsequent Intents inside your Service. I see two solutions:

  1. Use IntentService and save and restore this state inside onHandleIntent.
  2. Use started Service, and hold this state as a field inside your Service class. To prevent ANRs, process the Intents outside of UI thread, just like the IntentService does. To keep the Service running, just remove the stopSelf call from handleMessage.

If you can get away with restoring and saving state for each processed Intent, the first solution is safer, because your Service may be killed by the OS in case of running out of memory.

Upvotes: 0

Related Questions