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 on开发者_StackOverflowly right way.
-Lev
The correct way is #2. That's because as soon as you leave onReceive
application process might be killed. And your TimerTask
won't help in such case.
As an alternative solution, use AlarmManager
and its set
function to schedule pending service intent. This is probably the best solution in your case.
精彩评论