Android's AlarmManager Javadoc states
When an alarm goes off, the Intent that had been registered for it is broadcast by the system,
There is an AlarmService
(package com.example.android.apis.app) in the API demos supplied with Android which demonstrate AlarmService in use.
In it we have the following (edited for clarity):
PendingIntent mAlarmSender = PendingIntent.getService(AlarmService.this,
0, new Intent(AlarmService.this, AlarmService_Service.class), 0);
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, 30*1000, mAlarmSender);
So in this example it doesn't do a PendingIntent mAlarmSender = PendingIntent.getBroadcast(...);
instead it does a getService
which the Javadoc never alludes to.
The reason I am asking about this is because of the implications of the CPU wake lock. The Javadoc says that the AlarmManger's wake lock will be released once a Broadcast receiver's onReceive()
returns.
What I am wondering is what are the wake lock implications if you use an Alarm like in the example? The Javadoc doesn't seem to address this. If anything it seems to imply that you must use the broadcast technique when setting alarms.
A wakelock is a powerful concept in Android that allows the developer to modify the default power state of their device. The danger of using a wakelock in an application is that it will reduce the battery life of a device.
To release the wake lock, call wakelock. release() . This releases your claim to the CPU. It's important to release a wake lock as soon as your app is finished using it to avoid draining the battery.
Open Settings. Tap Display. Tap Sleep or Screen timeout. Select how long you want your Android smartphone or tablet screen to stay on before turning off due to inactivity.
What I am wondering is what are the wake lock implications if you use an Alarm like in the example?
There are no guarantees that your service will get control before the device falls asleep.
If anything it seems to imply that you must use the broadcast technique when setting alarms.
For _WAKEUP
alarms, yes, as that is the only path in which we are guaranteed to get control while the device is still awake.
Since the work to be done by the _WAKEUP
alarm is typically beyond the scope of what you can safely do in onReceive()
of a manifest-registered BroadcastReceiver
, a common pattern is to delegate the work to an IntentService
. To that end, I have packaged up WakefulIntentService
, to implement the pattern for safely passing control to an IntentService
and keeping the device awake long enough for the service to do its work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With