Alarm Manager Example
⚡TLDR
Schedule tasks in Android using AlarmManager with these steps:
- Create Intent for the action to execute.
- Encase it in a PendingIntent.
- Access AlarmManager by
context.getSystemService(Context.ALARM_SERVICE)
. - Schedule with
set()
,setRepeating()
orsetExact()
.
Setting a 10-second alarm:
Note: Android 6.0 and above should use setExactAndAllowWhileIdle()
for precision during Doze Mode.
Creating a simple Alarm
Here's a simple alarm setup that triggers a broadcast:
- Create a BroadcastReceiver to respond when alarm fires:
- Register the BroadcastReceiver in
AndroidManifest.xml
:
- Set up the alarm using the Fast Setup instructions above.
Advanced Alarm Setup
The created alarm is great but it vanishes after a device reboot. For a more persistent alarm setup:
- Create a Boot receiver: This resets the alarms after the device reboots.
- Register Boot Receiver in your
AndroidManifest.xml
:
- Permissions: Your app needs explicit permissions for using wake locks. Add these in your
Manifest.xml
:
Advanced Alarm Handling
Wake lock with BroadcastReceiver: Ensure tasks run when alarm fires by keeping the CPU running:
IntentService and AlarmManager combo:
For tasks that run a long time, use IntentService
with AlarmManager:
Managing multiple alarms:
Ensure unique PendingIntent request codes and use custom Intent
action strings:
Critical Tips for Alarm Management
- Doze Mode awareness for newer Android versions.
- Use
SystemClock.elapsedRealtime()
to schedule inexact repeating alarms that don't need to wake the device up. - Be mindful of the impact of frequent alarms on battery life and user experience.
Linked
Linked
Was this article helpful?