The problem hiding in your messenger’s battery graph
Every app with a persistent connection eventually writes the same code. A socket must stay warm, the server wants a ping every few minutes, and the radio will happily go to sleep if you let it. The pragmatic answer for years has been a partial wake lock held for as long as the connection is “active,” often wrapped in a foreground service so the OS leaves you alone.
It works. It is also a flat line on the wake-lock track of every battery trace you will ever open: the CPU is pinned awake to do a few milliseconds of useful work per cycle.
Android 17 (API 37) adds an overload of AlarmManager.setExactAndAllowWhileIdle that takes a callback instead of a PendingIntent:
setExactAndAllowWhileIdle(
type: Int,
triggerAtMillis: Long,
tag: String?,
executor: Executor,
listener: AlarmManager.OnAlarmListener,
)
Google’s Android 17 feature overview positions it as a way for apps that rely on continuous wake locks for periodic work, such as messengers maintaining sockets, to stop doing so (Android 17 features and APIs). OnAlarmListener itself is old; listener variants of set, setExact, and setWindow have existed for years. What is new is that the Doze-piercing variant now exists in listener form.
This post covers why that matters, what you give up, how to migrate without regressions, and how to prove the win on your own devices.
Two lifecycles, two contracts
A PendingIntent alarm is a durable token. The system holds it, and when the alarm fires the system does the work of reaching your code: it sends the broadcast (or starts the service the intent points at) and cold-starts your process if it is gone. Background-start restrictions still apply, which is why modern code targets a broadcast or foreground-service PendingIntent rather than a plain service.
A listener alarm is a live callback. The system holds a binder reference to an object inside your process. When the alarm fires, it calls that object. There is no token that can summon a process that no longer exists.
That one difference drives every design decision below.
Why this can reduce wake locks
With the PendingIntent path, an alarm firing into a receiver gives you a short system-held wake window and then leaves you to manage the CPU yourself. Teams that distrust that window (or need more than a few seconds) respond by holding their own wake lock across the whole interval, so that the process is guaranteed to be around and awake at the next tick.
The listener path removes the reason for that defensive posture, but only if your process is guaranteed alive anyway. If you are already running a connection in a live process, you no longer need to keep the CPU awake between beats to be sure you will be called. The alarm wakes the device, calls your listener, and you hold a wake lock only for the work itself.
In short: the wake lock moves from “the whole interval” to “the beat.”
When must the process be alive?
Here is the contract in scenario form.
Read the second row twice. A PendingIntent alarm outlives your process; a listener alarm does not. (Verify on your target builds: kill your process with adb shell am kill <package> while an alarm is pending and watch dumpsys alarm.)
This gives you a clean rule for choosing:
- The work needs a live process anyway (an open socket, an in-memory session, a warm cache): the listener is a good fit.
-
The work must happen even if the process is gone (a reminder, a scheduled sync that rebuilds its own state): stay on
PendingIntentor WorkManager.
Many apps have both kinds of work. Treat the choice as per-workload, not per-app.
Migration, step by step
Step 0: the legacy implementation
Here is the shape most codebases have today. It is a receiver-driven loop that re-arms itself.
class LegacyHeartbeat(private val context: Context) : Heartbeat {
private val alarmManager = context.getSystemService<AlarmManager>()!!
private fun beatIntent(): PendingIntent = PendingIntent.getBroadcast(
context,
REQUEST_CODE,
Intent(context, HeartbeatReceiver::class.java).setAction(ACTION_BEAT),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
override fun arm(delay: Duration) {
alarmManager.setExactAndAllowWhileIdle(
AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + delay.inWholeMilliseconds,
beatIntent(),
)
}
override fun disarm() = alarmManager.cancel(beatIntent())
private companion object {
const val REQUEST_CODE = 42
const val ACTION_BEAT = "com.example.chat.BEAT"
}
}
class HeartbeatReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val pending = goAsync()
// Hand off to the connection layer, then finish the broadcast.
ConnectionHub.from(context).beat { pending.finish() }
}
}
Note what the surrounding architecture usually adds: a foreground service and a long-held partial wake lock, because the receiver’s lifetime is too short to finish a reconnect-and-resync on a flaky network.
Step 1: a shared contract
Introduce a seam so both implementations can coexist during rollout.
interface Heartbeat {
fun arm(delay: Duration = DEFAULT_INTERVAL)
fun disarm()
companion object {
val DEFAULT_INTERVAL: Duration = 5.minutes
}
}
Step 2: the listener implementation
@RequiresApi(37)
class ListenerHeartbeat(
context: Context,
private val scope: CoroutineScope,
private val beat: suspend () -> Unit,
) : Heartbeat {
private val appContext = context.applicationContext
private val alarmManager = appContext.getSystemService<AlarmManager>()!!
private val powerManager = appContext.getSystemService<PowerManager>()!!
private val executor: ExecutorService = Executors.newSingleThreadExecutor()
private val mainHandler = Handler(Looper.getMainLooper())
private val stateLock = Any()
@Volatile private var interval: Duration = Heartbeat.DEFAULT_INTERVAL
@Volatile private var closed = false
// One stable instance: the platform identifies the alarm by this object.
private val listener = AlarmManager.OnAlarmListener { onAlarm() }
override fun arm(delay: Duration) {
synchronized(stateLock) {
if (closed) return
interval = delay
val triggerAt = SystemClock.elapsedRealtime() + delay.inWholeMilliseconds
if (!alarmManager.canScheduleExactAlarms()) {
degrade(triggerAt)
return
}
try {
alarmManager.setExactAndAllowWhileIdle(
AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAt, TAG, executor, listener,
)
} catch (e: SecurityException) {
Log.w(TAG, "Exact alarm denied; degrading", e)
degrade(triggerAt)
}
}
}
override fun disarm() {
alarmManager.cancel(listener)
}
fun close() {
synchronized(stateLock) {
closed = true
alarmManager.cancel(listener)
}
executor.shutdown()
}
private fun onAlarm() {
// Once the callback returns, the system's wake window ends. Take a short
// wake lock of our own for the async work.
val wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "$TAG:beat").apply {
setReferenceCounted(false)
acquire(WAKE_BUDGET.inWholeMilliseconds)
}
scope.launch {
try {
withTimeoutOrNull(WAKE_BUDGET) { beat() }
?: Log.w(TAG, "Beat exceeded $WAKE_BUDGET; releasing wake lock")
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
Log.e(TAG, "Beat failed", e)
} finally {
if (wakeLock.isHeld) wakeLock.release() // the timeout may already have freed it
if (isActive) arm(interval) // arm() itself ignores a closed heartbeat
}
}
}
// Inexact and Doze-deferred, but the chain keeps going while the process lives.
private fun degrade(triggerAt: Long) {
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAt, TAG, listener, mainHandler)
}
private companion object {
const val TAG = "ListenerHeartbeat"
val WAKE_BUDGET = 20.seconds
}
}
Imports for this file: kotlin.time.Duration, kotlin.time.Duration.Companion.seconds, kotlinx.coroutines.*, java.util.concurrent.*. Everything here uses kotlin.time.Duration only, so no java.time types are involved.
A few details worth defending in code review:
-
Single listener instance. The system tracks the alarm by listener identity. Creating a new lambda per
arm()call is how you accumulate duplicates. (Verify withdumpsys alarmthat re-arming leaves one entry.) - Dedicated single-thread executor. Do not pass a direct executor: it would run your callback on a binder thread. Do not pass the main executor if the callback ever does I/O; here it only launches a coroutine, but a private executor keeps that guarantee local.
-
finallyre-arms. The next alarm is scheduled whether the beat succeeded, timed out, or threw. -
isActiveandclosedchecks. A cancelled scope or a closed heartbeat must not resurrect the chain.arm()andclose()share a lock so an in-flight beat cannot re-register the listener afterclose()has cancelled it. -
@Volatilestate.intervalis written by callers and read on the coroutine dispatcher. -
Bounded wake lock.
acquire(timeout)is a backstop; thefinallyrelease is the normal path, guarded byisHeldbecause the timeout may already have released it. (On stock AOSP a non-reference-counted release is harmless, but some OEM builds are stricter, and the guard costs nothing.) -
Hoisted
Handler. Allocate it once rather than on everydegrade()call. -
Always call
close(). The executor owns a thread that lives until it is shut down.
Step 3: choose at the seam
fun heartbeatFor(
context: Context,
scope: CoroutineScope,
beat: suspend () -> Unit,
): Heartbeat =
if (Build.VERSION.SDK_INT >= 37) {
ListenerHeartbeat(context, scope, beat)
} else {
LegacyHeartbeat(context)
}
You need compileSdk = 37 to reference the new overload. Keep the legacy class and its receiver registered in the manifest; devices below API 37 still use them.
Step 4: make process death survivable
The listener path trades durability for lower wake time, so you owe the system a recovery story. The simplest robust one is to persist the last successful beat and reconcile whenever your process starts for any reason:
class HeartbeatReconciler(
private val store: BeatStore, // persists epoch millis of the last good beat
private val heartbeat: Heartbeat,
private val nowMillis: () -> Long = System::currentTimeMillis,
) {
suspend fun onProcessStart(beatNow: suspend () -> Unit) {
val last = store.lastBeatEpochMillis() ?: 0L
val overdue = (nowMillis() - last).milliseconds > Heartbeat.DEFAULT_INTERVAL * 2
if (overdue) beatNow()
heartbeat.arm()
}
}
The reconciler deliberately uses epoch millis and kotlin.time.Duration (kotlin.time.Duration.Companion.milliseconds) so no java.time desugaring is needed on pre-API 26 targets. Pair it with a low-frequency durable trigger (WorkManager periodic work, or a BOOT_COMPLETED receiver) whose only job is to get your process running again. The listener makes the steady state cheap; the durable trigger makes the failure state recoverable.
Failure modes I would expect to see in production
A few deserve more than a card.
The silent chain break. In the legacy design, a crash in the receiver rarely kills the loop because the next PendingIntent is typically scheduled before the work runs. In the listener design, the natural place to re-arm is after the work, which means any uncaught exception ends the chain. Re-arm in finally, or re-arm before the work and let the beat reschedule itself only if the cadence needs to change.
The early return. The callback is not a coroutine. If onAlarm() launches async work and returns, nothing in the platform knows your handshake is half done. That is why the example takes its own bounded wake lock. The goal is not to eliminate wake locks; it is to make them proportional to work.
The leak. system_server only holds a binder proxy for your listener, but inside your own process the AlarmManager instance keeps the listener (and its wrapper) in a map until the alarm fires or you call cancel(). A lambda that captures an Activity or a bound Service therefore pins it for as long as the alarm is pending. Capture only application-scoped objects, and cancel in the same lifecycle callback that created the registration.
Doze arithmetic. Allow-while-idle alarms are rate-limited while the device is idle. Do not design a 30-second heartbeat on the assumption this API exempts you. Pick an interval your server and any NAT in the path can tolerate even when beats arrive late, and check your app’s standby bucket behavior on real hardware.
Permission drift. Exact alarms are gated by permission on modern Android. Check canScheduleExactAlarms() before scheduling, catch SecurityException, and have a degraded mode. Also listen for permission-state changes so you can re-arm exactly when the user grants it back. (Check the current reference for any exemption that applies to the listener overload on your target SDK.)
Reading the battery graph, before and after
I have not run a controlled benchmark for this post, so the figure below is a model of the expected shape, not data. Its purpose is to show what to look for in your own traces.
Capture your own
Use a fixed scenario (screen off, on battery, same network, same server behavior) and run each build for the same duration.
# 1. Reset counters and unplug from charger (or use a wireless ADB session)
adb shell dumpsys batterystats --reset
# 2. Put the device in idle quickly for repeatable Doze behavior
adb shell dumpsys deviceidle force-idle
# 3. Let the app run for 60+ minutes, then dump
adb shell dumpsys batterystats --checkin > before.txt # repeat for "after"
# 4. Inspect scheduled alarms and what the system thinks is pending
adb shell dumpsys alarm | grep -A6 com.example.chat
What to compare:
-
Wake lock time for your package:
batterystatsper-UID wake lock section, or Battery Historian. -
Number and spacing of alarm deliveries:
dumpsys alarm, per-package stats. - CPU wakeups attributed to you: a Perfetto trace with power and suspend/resume data sources.
- Behavioral regressions: your own beat-success and reconnect-latency metrics.
The last item matters most. A wake-lock graph that improves while reconnect latency doubles is not a win; it is a trade you did not price. Ship the migration behind a remote flag and compare cohorts on both axes.
Rollout checklist
- Raise
compileSdkto 37, keeptargetSdkunchanged for the first release. - Land the
Heartbeatseam with only the legacy implementation. Verify no behavior change. - Add
ListenerHeartbeatbehind a flag, default off. - Add the reconciler and the durable recovery trigger before enabling the flag.
- Enable for a small cohort on API 37 devices; watch beat success rate, reconnect latency, ANRs, and wake-lock time.
- Remove the long-held wake lock only after the cohort data confirms the loop is healthy without it.
Takeaways
- The new overload lets a live process be called back without holding the CPU awake between beats. That is its whole value.
- It does not replace
PendingIntentalarms. It cannot revive a dead process, so durable work stays durable. - The migration is easy; the failure handling is the real work. Re-arm in
finally, bound your wake lock, reconcile on start. - Measure on your own devices. Treat any wake-lock graph, including mine, as a hypothesis until it is yours.
Sources
- Android Developers, Features and APIs: Android 17, section on listener support for allow-while-idle alarms.
- Android Developers,
AlarmManagerAPI reference, including thesetExactAndAllowWhileIdle(int, long, String, Executor, OnAlarmListener)overload andcancel(OnAlarmListener).
📘 Master Your Next Technical Interview
Since Java is the foundation of Android development, mastering DSA is essential. I highly recommend “Mastering Data Structures & Algorithms in Java”. It’s a focused roadmap covering 100+ coding challenges to help you ace your technical rounds.
- E-book: Available on Google Play
- Kindle Edition: Available on Amazon
- Topmate: Available on Topmate
- Also available in Paperback & Hardcover.





Top comments (0)