tezvyn:

AlarmManager: Scheduling Precise Future Tasks in Android

AI-drafted, machine-checkedSource: developer.android.comintermediate

AlarmManager is Android's system-wide alarm clock for your app, letting you run code at a specific time, even if your app is closed. Use it for time-sensitive tasks like calendar notifications. The footgun: alarms are wiped on reboot and must be re-registered.

WHY IT EXISTS: Applications often need to perform operations long after they are closed, triggered by the passage of time. Android needed a way for apps to schedule these future tasks with the OS itself, ensuring they run even if the app's process is killed or the device is asleep.

THE MENTAL MODEL: Think of AlarmManager as setting an alarm on a real, physical clock that belongs to the Android system, not your app. You tell the system, "At 8:00 AM, please run this specific piece of my code." The system then takes full responsibility for waking the device (if requested) and triggering your code at or near that time.

HOW IT WORKS: You get an instance of AlarmManager from the system context. You then create a PendingIntent, which is a token that gives the system permission to execute a piece of your app's code on its behalf. This intent might start a service or send a broadcast. You then call a method like setExactAndAllowWhileIdle(), passing the trigger time, the type of alarm (e.g., RTC_WAKEUP to wake the device from sleep), and your PendingIntent. When the alarm fires, the system executes the PendingIntent.

WHEN TO USE IT: Use AlarmManager for tasks that are user-visible and must run at a specific, precise time. The canonical use cases are alarm clock apps and calendar event notifications. These are tasks where being a few minutes late ruins the user experience.

WHEN NOT TO USE IT: Do not use AlarmManager for deferrable background work that doesn't need to run at an exact time, like syncing data or pre-fetching content. For that, WorkManager is the modern, recommended solution. WorkManager respects battery optimizations and system health, can chain tasks, and handles constraints like network availability. Using AlarmManager for frequent, non-critical tasks is a major cause of battery drain and is restricted by modern Android versions.

ONE CANONICAL EXAMPLE: To set a precise alarm that wakes the device, an app first requests the SCHEDULE_EXACT_ALARM permission. It then gets the AlarmManager service, creates a PendingIntent pointing to a BroadcastReceiver, and calls alarmManager.setExactAndAllowWhileIdle(triggerAtMillis, pendingIntent). The receiver handles the event, perhaps by showing a notification. Critically, after a device reboot, a separate BOOT_COMPLETED receiver must run to re-schedule this same alarm, as all alarms are cleared on restart.

Read the original → developer.android.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.