I have a case in which I have to start some non-UI action N seconds after power has been connected to the device. That action could be also started by user via UI.
I have a BroadcastReceiver defined in AndroidManifest.xml which listens for ACTION_POWER_CONNECTED.
I have a service that does required action on onStartCommand. My question is – what is the right way to start that service in case of when action is triggered by broadcast?
I have two options in mind:
-
One-shot timer task. However I think it might be wrong because of according to docs, I could’t start any async tasks from BroadcastReceiver.
-
Redesign service:
- start action at onStartCommand, if action was triggered by user
- start timer task and do action at timer shot – same logic as in 1. but inside service – if action was triggered by broadcast.
I am inclined to 2. It will make code a bit more complex, but it seems it is only right way.
-Lev
The correct way is #2. That’s because as soon as you leave
onReceiveapplication process might be killed. And yourTimerTaskwon’t help in such case.As an alternative solution, use
AlarmManagerand itssetfunction to schedule pending service intent. This is probably the best solution in your case.