Alarms and exact timing
Why it matters
- Alarms are the tool for "at 07:00" and "in exactly 20 minutes". Picking the wrong method means a reminder that fires 30 minutes late in Doze, or a crash on Android 12+.
- Exact alarms are now a special permission:
SCHEDULE_EXACT_ALARM(Android 12) is denied by default for most new installs from Android 14, andUSE_EXACT_ALARM(Android 13) is limited by Play policy to alarm, timer and calendar apps. - All alarms are cleared on reboot. A missing
BOOT_COMPLETEDreschedule is a classic "reminders stopped working" bug. - Interviewers ask when an alarm beats WorkManager, how Doze treats each method, and how you handle a denied exact-alarm permission.
The simple explanation
- You hand a note to the building's night porter (the system): "knock on my door at 10:00".
- Inexact: the porter may knock any time around 10:00, combining it with other rounds to save effort.
- Exact: the porter knocks at 10:00, but only if you hold a permit (
SCHEDULE_EXACT_ALARMorUSE_EXACT_ALARM). - At night the building is in quiet mode (Doze): normal notes wait until the next scheduled round. Only notes marked "allow while idle", or a real alarm clock, are delivered during quiet hours.
- If the building loses power (reboot), the porter's notebook is wiped, and you must hand in your notes again.
AlarmManager fires a PendingIntent at a time you choose. Alarms live in the system, so they fire even if your process is dead, but they are cleared on reboot and when the user force-stops the app.
Inexact vs exact. Since API 19 (target 19), set() and setRepeating() are inexact: the system may batch them. setWindow() fires within a window you give; from Android 12 (target 31), windows shorter than 10 minutes are extended to 10 minutes. setExact(), setExactAndAllowWhileIdle() and setAlarmClock() fire at the requested time.
Doze (API 23+). While the device is idle in Doze, normal alarms, including setExact(), are deferred to the next maintenance window. setAndAllowWhileIdle() and setExactAndAllowWhileIdle() can fire during Doze, but the system limits how often (roughly once per 9 minutes per app while idle). setAlarmClock() is for alarms the user sets: the system shows it as the next alarm and leaves Doze shortly before it.
Exact-alarm permissions.
SCHEDULE_EXACT_ALARM(Android 12, API 31): needed on target 31+ forsetExact*()andsetAlarmClock(); without it they throwSecurityException. It is "special app access" the user can turn off. It was granted at install on Android 12 and 13; from Android 14 it is denied by default for most newly installed apps targeting 33+.USE_EXACT_ALARM(Android 13, API 33): granted automatically and cannot be revoked, but Google Play allows it only for alarm clock, timer and calendar apps.- Check
alarmManager.canScheduleExactAlarms()(API 31+) before scheduling, and send the user toSettings.ACTION_REQUEST_SCHEDULE_EXACT_ALARMif the feature needs it. When the user grants access, the app receivesACTION_SCHEDULE_EXACT_ALARM_PERMISSION_STATE_CHANGED; when they revoke it, the app is stopped and its exact alarms are cancelled.
Time base. RTC and RTC_WAKEUP use wall-clock time (System.currentTimeMillis()), right for "at 09:00". ELAPSED_REALTIME and ELAPSED_REALTIME_WAKEUP count from boot (SystemClock.elapsedRealtime()) and ignore clock changes, right for "in 30 minutes". Only the _WAKEUP types wake a sleeping device; the others wait until the device is awake anyway. _WAKEUP does not bypass Doze.
| Method | Exact | Fires during Doze | Permission on target 31+ |
|---|---|---|---|
set() | No | No, deferred | None |
setWindow() | Within the window | No, deferred | None |
setAndAllowWhileIdle() | No | Yes, rate-limited | None |
setExact() | Yes | No, deferred | SCHEDULE_EXACT_ALARM or USE_EXACT_ALARM |
setExactAndAllowWhileIdle() | Yes | Yes, rate-limited | SCHEDULE_EXACT_ALARM or USE_EXACT_ALARM |
setAlarmClock() | Yes | Yes, leaves Doze | SCHEDULE_EXACT_ALARM or USE_EXACT_ALARM |
When to choose an alarm. Use an alarm when the user expects something at a specific time: a reminder, an alarm clock, a calendar event. Use WorkManager for work that must finish but can run late, including periodic work (15-minute minimum). An alarm can enqueue WorkManager work when it fires if the follow-up work is heavy.
Notes
- Exact alarms cost battery and need special access. Use them only for user-facing timing; for "sometime soon" use
setWindow(),setAndAllowWhileIdle()or WorkManager. - On target 31+, calling
setExact(),setExactAndAllowWhileIdle()orsetAlarmClock()without exact-alarm access throwsSecurityException. CheckcanScheduleExactAlarms()first and have an inexact fallback. - From Android 14,
SCHEDULE_EXACT_ALARMis denied by default for most new installs of apps targeting 33+. Explain the feature, then openSettings.ACTION_REQUEST_SCHEDULE_EXACT_ALARMwith your package URI. - Listen for
AlarmManager.ACTION_SCHEDULE_EXACT_ALARM_PERMISSION_STATE_CHANGEDto reschedule exact alarms when access is granted. Revoking access stops the app and cancels its exact alarms. - All alarms are cleared on reboot and on force-stop. Persist what you scheduled (Room or DataStore) and reschedule on
BOOT_COMPLETED, which needs theRECEIVE_BOOT_COMPLETEDpermission. - Use
RTC_WAKEUPfor wall-clock times and compute them withjava.timein the user's zone. Reschedule onACTION_TIMEZONE_CHANGEDandACTION_TIME_CHANGED, which are still delivered to manifest receivers. - Use
ELAPSED_REALTIME_WAKEUPfor relative delays ("in 20 minutes"); it is not affected by clock or timezone changes. setRepeating()is not deprecated, but since API 19 it is inexact, and it is deferred in Doze. For exact repeating behaviour, schedule one exact alarm and set the next one when it fires.- An alarm is replaced when you schedule it again with an equal
PendingIntent: the same request code and an intent that matches by action, data, type, component and categories (extras are ignored). Use a distinct request code per alarm, andcancel(pendingIntent)to remove one. - An exact alarm firing for a user-requested action is one of the exemptions that allow starting a foreground service from the background on Android 12+.
Code example
A reminder scheduler that computes the next 09:00 in the user's zone, uses an exact alarm when allowed and an inexact Doze-safe alarm otherwise, plus a receiver that reschedules after reboot, time changes and a permission grant. It assumes minSdk 26.
// ReminderScheduler.kt
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings
import java.time.LocalTime
import java.time.ZoneId
import java.time.ZonedDateTime
class ReminderScheduler(private val context: Context) {
private val alarmManager = context.getSystemService(AlarmManager::class.java)
fun canScheduleExact(): Boolean =
Build.VERSION.SDK_INT < Build.VERSION_CODES.S || alarmManager.canScheduleExactAlarms()
// triggerAtMillis is wall-clock time, so use RTC_WAKEUP
fun schedule(reminderId: Int, triggerAtMillis: Long) {
val pi = pendingIntent(reminderId)
if (canScheduleExact()) {
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerAtMillis, pi)
} else {
// No exact access: fires some time after triggerAt, still allowed in Doze
alarmManager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerAtMillis, pi)
}
}
fun cancel(reminderId: Int) = alarmManager.cancel(pendingIntent(reminderId))
// Call after explaining why the feature needs exact timing
fun openExactAlarmSettings() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
context.startActivity(
Intent(Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM, Uri.parse("package:${context.packageName}"))
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
)
}
}
private fun pendingIntent(reminderId: Int): PendingIntent = PendingIntent.getBroadcast(
context,
reminderId, // one alarm per reminder
Intent(context, ReminderReceiver::class.java).putExtra(EXTRA_REMINDER_ID, reminderId),
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
)
companion object {
const val EXTRA_REMINDER_ID = "reminder_id"
}
}
// The next time the wall clock shows `time` in `zone`
fun nextOccurrence(time: LocalTime, zone: ZoneId = ZoneId.systemDefault()): Long {
val now = ZonedDateTime.now(zone)
var next = now.with(time).withSecond(0).withNano(0)
if (!next.isAfter(now)) next = next.plusDays(1)
return next.toInstant().toEpochMilli()
}
// RescheduleReceiver.kt
import android.app.AlarmManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import androidx.work.ExistingWorkPolicy
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
class RescheduleReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
when (intent.action) {
Intent.ACTION_BOOT_COMPLETED,
Intent.ACTION_TIME_CHANGED,
Intent.ACTION_TIMEZONE_CHANGED,
AlarmManager.ACTION_SCHEDULE_EXACT_ALARM_PERMISSION_STATE_CHANGED -> {
// Reading Room is I/O: hand it to a worker that recomputes and reschedules every reminder
WorkManager.getInstance(context).enqueueUniqueWork(
"reschedule_reminders",
ExistingWorkPolicy.REPLACE,
OneTimeWorkRequestBuilder<RescheduleRemindersWorker>().build(),
)
}
}
}
}<!-- AndroidManifest.xml -->
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application>
<receiver android:name=".ReminderReceiver" android:exported="false" />
<receiver android:name=".RescheduleReceiver" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.TIME_SET" />
<action android:name="android.intent.action.TIMEZONE_CHANGED" />
<action android:name="android.app.action.SCHEDULE_EXACT_ALARM_PERMISSION_STATE_CHANGED" />
</intent-filter>
</receiver>
</application>canScheduleExact()guards every exact call, so a denied permission gives a late reminder instead of aSecurityException.- Reminders use
RTC_WAKEUPwith a time computed byjava.timein the user's zone;ELAPSED_REALTIMEwould be wrong for "at 09:00", because it cannot follow wall-clock or timezone changes. Intent.ACTION_TIME_CHANGEDis the action stringandroid.intent.action.TIME_SET. The time and timezone broadcasts are among the implicit broadcasts still delivered to manifest receivers.- The receiver only enqueues work; reading the stored reminders and recomputing their times happens in a worker, off the main thread.
Run the idea in plain Kotlin
A simplified model of how Doze treats each method while the device is idle from minute 0 to 60, with one maintenance window at minute 30. Normal alarms wait for the window, "allow while idle" alarms fire but at most once per 9 minutes, and an alarm clock fires on time.
enum class Method(val allowWhileIdle: Boolean, val alarmClock: Boolean) {
SET(false, false),
SET_EXACT(false, false),
SET_AND_ALLOW_WHILE_IDLE(true, false),
SET_EXACT_AND_ALLOW_WHILE_IDLE(true, false),
SET_ALARM_CLOCK(false, true)
}
data class Alarm(val name: String, val method: Method, val triggerMin: Int)
const val DOZE_END = 60
const val IDLE_GAP_MIN = 9
val maintenanceWindows = listOf(30)
fun inDoze(minute: Int) = minute in 0 until DOZE_END
fun main() {
val alarms = listOf(
Alarm("sync", Method.SET, 10),
Alarm("timer", Method.SET_EXACT, 12),
Alarm("pill", Method.SET_EXACT_AND_ALLOW_WHILE_IDLE, 15),
Alarm("pill-2", Method.SET_EXACT_AND_ALLOW_WHILE_IDLE, 18),
Alarm("wake-up", Method.SET_ALARM_CLOCK, 40),
Alarm("digest", Method.SET, 45),
Alarm("evening", Method.SET_EXACT, 75)
)
var lastIdleFire = -100
for (a in alarms.sortedBy { it.triggerMin }) {
val fireAt = when {
!inDoze(a.triggerMin) -> a.triggerMin
a.method.alarmClock -> a.triggerMin
a.method.allowWhileIdle -> {
val t = maxOf(a.triggerMin, lastIdleFire + IDLE_GAP_MIN)
lastIdleFire = t
t
}
else -> (maintenanceWindows.filter { it >= a.triggerMin } + DOZE_END).first()
}
val note = if (fireAt == a.triggerMin) "on time" else "late by " + (fireAt - a.triggerMin) + " min"
println(a.name.padEnd(8) + a.method.name.padEnd(31) + "asked " + a.triggerMin + ", fired " + fireAt + " (" + note + ")")
}
println("Reboot: every pending alarm is cleared; reschedule on BOOT_COMPLETED")
}Expected output:
sync SET asked 10, fired 30 (late by 20 min)
timer SET_EXACT asked 12, fired 30 (late by 18 min)
pill SET_EXACT_AND_ALLOW_WHILE_IDLE asked 15, fired 15 (on time)
pill-2 SET_EXACT_AND_ALLOW_WHILE_IDLE asked 18, fired 24 (late by 6 min)
wake-up SET_ALARM_CLOCK asked 40, fired 40 (on time)
digest SET asked 45, fired 60 (late by 15 min)
evening SET_EXACT asked 75, fired 75 (on time)
Reboot: every pending alarm is cleared; reschedule on BOOT_COMPLETED
In production
- A medication app scheduled each dose with
setExactAndAllowWhileIdle()and kept no record of what it had scheduled. - Users reported missed doses after their phone restarted or updated overnight. Alarms are cleared on reboot, and the app only scheduled reminders when the user edited them.
- Nothing crashed, so the problem only showed up in reviews and support emails.
- They stored every reminder (id, local time, repeat rule) in Room as the source of truth, and added a
BOOT_COMPLETEDreceiver withRECEIVE_BOOT_COMPLETEDthat enqueues a worker to reschedule all of them. - After each alarm fires, the receiver schedules the next dose, so the schedule never depends on a repeating alarm.
- They tested by scheduling a reminder, rebooting the emulator, and checking the alarm with
adb shell dumpsys alarm.
- A to-do app with "remind me at" times called
setExact()without checking anything. On Android 14, new installs crashed withSecurityException, becauseSCHEDULE_EXACT_ALARMis denied by default there. - A quick fix wrapped the call in
try/catchand did nothing in the catch, so reminders on new installs silently never fired. - Older installs worked, because Android 12 and 13 had granted the permission at install.
- They check
canScheduleExactAlarms()before scheduling. If it is false, they usesetAndAllowWhileIdle()withRTC_WAKEUP, so the reminder still fires, possibly a few minutes late. - The reminder screen explains that exact reminders need "Alarms & reminders" access and opens
Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM. A receiver forACTION_SCHEDULE_EXACT_ALARM_PERMISSION_STATE_CHANGEDreschedules all reminders as exact when access is granted. - They did not add
USE_EXACT_ALARM, because Play policy allows it only for alarm clock, timer and calendar apps.
Common mistakes
- Calling setExact() without checking access. On target 31+ it throws
SecurityExceptionwhen exact-alarm access is missing, which is the default for most new installs on Android 14. CheckcanScheduleExactAlarms()and fall back to an inexact alarm. - Forgetting to reschedule after reboot. All alarms are cleared. Persist the schedule and reschedule on
BOOT_COMPLETED(withRECEIVE_BOOT_COMPLETED). - Using ELAPSED_REALTIME for a wall-clock reminder. "At 09:00" must be
RTC_WAKEUP, computed in the user's zone and recomputed on time or timezone changes.ELAPSED_REALTIMEis for relative delays. - Expecting setExact() or _WAKEUP to fire in Doze. Both are deferred to the next maintenance window. Use
setExactAndAllowWhileIdle()or, for a user-set alarm clock,setAlarmClock(). - Declaring USE_EXACT_ALARM in a general app. It is granted automatically, but Google Play only allows it for alarm clock, timer and calendar apps, so the app can be rejected.
- Reusing one request code for different alarms. An equal
PendingIntentreplaces the earlier alarm, so only the last reminder fires. Use a distinct request code per alarm. - Using alarms for periodic background sync. Alarms do not retry, survive reboot or respect network conditions. Use WorkManager for sync and keep alarms for user-facing times.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“When would you choose AlarmManager over WorkManager?”
“What happens to alarms after a reboot, and how do you handle it?”
“A user on Android 14 says exact reminders never fire. What do you check?”
“When do you use RTC versus ELAPSED_REALTIME?”
Quiz
Which method lets a reminder fire at an exact time while the device is in Doze?
A to-do app targeting SDK 34 is newly installed on Android 14 and calls setExact() without checking anything. What happens?
A reminder must fire at 09:00 local time every day. Which time base fits?
What happens to pending AlarmManager alarms when the device reboots?
0 of 4 answered
Mini task
Reboot-proof reminder (15 min)
-
Add the scheduler. Copy
ReminderSchedulerandnextOccurrenceinto your project. Add aReminderReceiver(android:exported="false") that readsEXTRA_REMINDER_IDand logs it. -
Schedule a reminder. From a button, call
scheduler.schedule(1, System.currentTimeMillis() + 60_000). Runadb shell dumpsys alarm | grep <your.package>and confirm the alarm is listed; check logcat a minute later. -
Check the permission path. On an Android 14 emulator, turn off "Alarms & reminders" for the app in Settings, confirm
canScheduleExact()returns false, and that the inexact path is used without a crash. Then callopenExactAlarmSettings()and turn it back on. -
Persist the schedule. Save each reminder's id and trigger time in DataStore or Room when you schedule it, and remove it when it fires.
-
Reschedule after reboot. Add
RescheduleReceiverwith the manifest entries andRECEIVE_BOOT_COMPLETED. In its worker, read the saved reminders and callschedule()for each one that is still in the future. -
Test. Schedule a reminder 3 minutes ahead, reboot the emulator (
adb reboot), unlock it, and confirmdumpsys alarmlists the alarm again and it fires.
Done when: the reminder fires with exact access and without it, and it survives a reboot.