3
votes

I need to start a service to do long operation every x minutes. To do this I have an AlarmManager. Reading the docs at http://developer.android.com/reference/android/app/AlarmManager.html I found this:

The Alarm Manager holds a CPU wake lock as long as the alarm receiver's onReceive() method is executing. This guarantees that the phone will not sleep until you have finished handling the broadcast. Once onReceive() returns, the Alarm Manager releases this wake lock. This means that the phone will in some cases sleep as soon as your onReceive() method completes. If your alarm receiver called Context.startService(), it is possible that the phone will sleep before the requested service is launched. To prevent this, your BroadcastReceiver and Service will need to implement a separate wake lock policy to ensure that the phone continues running until the service becomes available.

So, how am I able to start a Service from an AlarmManager and be sure it starts. I know how to use WakeLocks, but there is no sense, I mean, I can use a wakelock in the Service but the doc says "it is possible that the phone will sleep before the requested service is launched"

2

2 Answers

3
votes

Use WakefulBroadcastReceiver or my WakefulIntentService.

The basic pattern is to have the AlarmManager invoke a BroadcastReceiver, which acquires the WakeLock and starts the service. The service is then responsible for releasing the WakeLock. WakefulBroadcastReceiver and WakefulIntentService simply bundle up that pattern and handle some edge cases.

0
votes

@Ton ,Are you sure that service is not starting if phone in sleep mode.I am not 100% sure but,As i know, it will be started, but you face problem if you are using internet in that service.