Most background-work bugs on Android are not coding bugs. They are routing bugs: the right work, sent to the wrong scheduler.
If you have shipped an Android app for more than a release cycle, you have probably written this sentence in a design doc: “we’ll just use a foreground service.” Or this one: “we’ll set an alarm and do the work in the receiver.” Both sound reasonable in a planning meeting. Both produce the same class of production incident a few months later: sync that silently stops on one OEM, a notification users cannot dismiss, a battery-drain complaint with no stack trace attached.
This post gives you a way to route work correctly, explains what Doze and App Standby actually do to each mechanism, and treats battery cost as something you model and measure rather than guess. The code is Kotlin and assumes you target a recent API level (34+), but the failure modes apply from API 23 onward.
1. Decision tree
Start with intent, not API surface. Ask three questions in order.
Is the user knowingly relying on this right now? Music playback, turn-by-turn navigation, a call, an upload the user just started and is watching. If yes, a foreground service is the honest answer. The ongoing notification is not a tax; it is the contract. You are telling the OS and the user that this work is happening on purpose.
Must it fire at a wall-clock moment the user expects? An alarm clock, a calendar event, a medication reminder. That is an alarm. Nothing else gives you the same timing semantics.
Is it deferrable, but must it survive process death and reboot? That is WorkManager’s home turf: persisted, constraint-aware, retried with backoff.
If none of the three apply, you probably do not need an OS-level guarantee at all. A coroutine in a lifecycle-bound scope is fine.
The dashed note in the diagram covers a fourth case that people routinely misroute: short work that a user triggers and that should begin now. That is expedited work in WorkManager, not a foreground service.
The combined pattern that keeps paying off
The mechanisms are not rivals. The most robust designs chain them: an alarm decides when, WorkManager decides how safely, and a foreground service exists only while the user is watching.
WorkManager: constraints and idempotence
// Imports omitted: java.io.IOException, java.util.concurrent.TimeUnit, androidx.work.*, dagger.assisted.* @HiltWorker class SyncWorker @AssistedInject constructor( @Assisted appContext: Context, @Assisted params: WorkerParameters, private val repository: SyncRepository, ) : CoroutineWorker(appContext, params) { override suspend fun doWork(): Result = try { // Idempotent by design: the system may run this more than once. repository.pullChangesSince(inputData.getLong(KEY_CURSOR, 0L)) Result.success() } catch (e: IOException) { if (runAttemptCount < MAX_ATTEMPTS) Result.retry() else Result.failure() } companion object { const val KEY_CURSOR = "cursor" private const val MAX_ATTEMPTS = 5 } } fun WorkManager.scheduleCatalogSync() { val request = PeriodicWorkRequestBuilder<SyncWorker>(1, TimeUnit.HOURS) .setConstraints( Constraints.Builder() .setRequiredNetworkType(NetworkType.UNMETERED) .setRequiresBatteryNotLow(true) .build() ) .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS) .build() enqueueUniquePeriodicWork( "catalog-sync", ExistingPeriodicWorkPolicy.KEEP, // CANCEL_AND_REENQUEUE would reset the period on every app start request, ) } Constructor injection only works because of @HiltWorker and Hilt's worker factory; with the default factory, WorkManager looks for a (Context, WorkerParameters) constructor and crashes at runtime if it is missing. Also note the catch block handles IOException only: any other exception fails the work, which is usually what you want for bugs but not for transient server errors you should map to retry().
Two production traps live in this snippet. First, enqueuing periodic work with a cancel-and-reenqueue policy (the deprecated REPLACE behavior many older tutorials show) restarts the period every time the app starts, so a user who opens the app every 50 minutes may never see an hourly run. Use KEEP, or UPDATE when the request itself changed and you want the new definition applied without losing the schedule. Second, a worker may run twice, or be stopped halfway and rerun. If your work is not idempotent, constraints and retries will make it worse, not better.
Expedited work instead of a “start now” foreground service
fun WorkManager.uploadReceiptNow(receiptId: String) { val request = OneTimeWorkRequestBuilder<UploadWorker>() .setInputData(workDataOf("id" to receiptId)) .setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST) .build() enqueueUniqueWork("upload-$receiptId", ExistingWorkPolicy.KEEP, request) } class UploadWorker(ctx: Context, params: WorkerParameters) : CoroutineWorker(ctx, params) { // Must be implemented: on API < 31 expedited work runs as a foreground service, and WorkManager can call this in other fallback paths too. override suspend fun getForegroundInfo(): ForegroundInfo = ForegroundInfo( NOTIFICATION_ID, buildUploadNotification(applicationContext), ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC, ) override suspend fun doWork(): Result { /* ... */ return Result.success() } } The failure mode here is the quota. Expedited jobs are rationed, and you must choose what happens when the quota is spent. RUN_AS_NON_EXPEDITED_WORK_REQUEST degrades gracefully into ordinary deferred work; DROP_WORK_REQUEST silently discards the job, which is almost never what a receipt upload wants.
Because WorkManager can fall back to its own SystemForegroundService, declare the matching type on it in your manifest (android:foregroundServiceType="dataSync" via tools:node="merge") and hold the FOREGROUND_SERVICE_DATA_SYNC permission when targeting API 34+. Skipping that is a classic crash that only appears on the fallback path.
Foreground service: the type is part of the API
class TripRecorderService : Service() { override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { ServiceCompat.startForeground( this, NOTIFICATION_ID, buildRecordingNotification(), ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION, ) scope.launch { /* collect location updates */ } return START_NOT_STICKY // be honest: if killed, don't resurrect into a state the user didn't ask for } private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) override fun onDestroy() { scope.cancel() // otherwise collectors outlive the service super.onDestroy() } override fun onBind(intent: Intent?): IBinder? = null } For apps targeting API 34+, every foreground service must declare a type in the manifest and hold the matching permission (a few types, such as shortService and specialUse, have lighter requirements). Starting one from the background throws ForegroundServiceStartNotAllowedException for apps targeting API 31+ (Android 12), unless you qualify for an exemption. The classic incident: a push message handler tries to start a service to "finish the job," works in every internal test because the app was in the foreground, and fails for real users whose app was idle.
Also watch the timeout rules. For apps targeting API 35, dataSync and mediaProcessing services share a budget of six hours per rolling 24 hours, after which the system calls onTimeout and you must stop the service. If you are using a foreground service as a poor man's long sync, you are building on a mechanism the platform is actively narrowing.
Alarms: schedule the trigger, not the work
fun AlarmManager.scheduleReminder( context: Context, triggerAtMillis: Long, reminderId: Long, isUserVisibleAlarm: Boolean, ) { // A unique data URI distinguishes PendingIntents; Long.hashCode() can collide. val pi = PendingIntent.getBroadcast( context, 0, Intent(context, ReminderReceiver::class.java) .setData(Uri.parse("reminder://$reminderId")) .putExtra("id", reminderId), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, ) when { // User-visible alarm: shows in the system UI, honored in Doze. isUserVisibleAlarm -> setAlarmClock(AlarmManager.AlarmClockInfo(triggerAtMillis, pi), pi) Build.VERSION.SDK_INT < 31 || canScheduleExactAlarms() -> setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerAtMillis, pi) else -> // Permission denied or revoked: degrade, don't crash. setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerAtMillis, pi) } } class ReminderReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { // The receiver's lifetime is seconds. Hand off immediately. WorkManager.getInstance(context).enqueue( OneTimeWorkRequestBuilder<ReminderWorker>() .setInputData(workDataOf("id" to intent.getLongExtra("id", -1))) .setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST) .build() ) } } Four alarm failure modes show up repeatedly in the wild:
- Permission drift. On Android 12+ exact alarms need
SCHEDULE_EXACT_ALARM, and users can revoke it. Starting with Android 14, most newly installed apps targeting API 33+ no longer get it pre-granted. Apps whose core function is an alarm clock or calendar can declareUSE_EXACT_ALARMinstead. Always checkcanScheduleExactAlarms()and keep a fallback path. - Reboots erase alarms. Re-arm from a
BOOT_COMPLETEDreceiver, and persist your schedule somewhere durable.BOOT_COMPLETEDarrives only after the user unlocks the device; a medication reminder that must ring before first unlock needsLOCKED_BOOT_COMPLETED, a direct-boot-aware receiver, and device-protected storage. - Doing real work in
onReceive. Foreground broadcasts get roughly ten seconds before an ANR, andgoAsync()only frees the main thread: it does not extend that ten-second deadline, so iffinish()is not called in time you still get the ANR. Enqueue and return; on a cold start, make sure WorkManager initialization is not what burns your budget. - Using exact alarms as a polling loop. “Every five minutes, exactly” is the single most expensive thing in this post. More on that in section 3.
2. Doze and standby behavior
Two separate systems throttle background work, and people conflate them constantly. Doze is about the device being idle. App Standby Buckets are about your app being ignored. You can be hit by either, or both.
Doze: the device is idle
Light Doze starts when the screen is off and the device is unplugged, even if it is moving. Deep Doze additionally requires the device to be stationary. In both modes the platform batches background activity into short maintenance windows, and in Deep Doze those windows get further apart the longer the device stays idle.
What that means in practice:
- WorkManager work waits for a maintenance window. Constraints are evaluated when the window opens, so work that looked eligible earlier can still sit there. Expedited work gets preferential treatment, bounded by quota.
- Standard alarms (
set,setExact) are deferred.setExactAndAllowWhileIdleandsetAndAllowWhileIdlefire, but the system rate-limits them to roughly one per nine minutes per app while idle.setAlarmClockis the exception for genuinely user-facing alarms. - A foreground service keeps its process alive, but Doze ignores your wake locks unless the app is on the battery-optimization allowlist. Network behavior for a foreground service depends on process state and OS version, so check it on a device in forced idle rather than assuming either way.
The incident pattern here is easy to recognize: “sync works on my desk and fails overnight.” The fix is almost never a bigger hammer. It is tolerating deferral, or using a high-priority push to wake the app for the specific event that matters.
Verify instead of trusting memory:
adb shell dumpsys deviceidle force-idle deep # push the device into deep idle (use 'light' for Light Doze) adb shell dumpsys deviceidle step # advance through the states adb shell dumpsys deviceidle unforce # return to normal App Standby Buckets: your app is ignored
Independently of Doze, the OS assigns your app to a bucket based on how recently and how meaningfully the user interacted with it. The lower the bucket, the more your jobs, alarms, and high-priority push messages are throttled.
This is the failure mode that most often wastes a week of debugging. Your QA devices keep the app in the Active bucket because the team opens it all day. A real user who opens it twice a month sits in Rare or lower, where jobs can be deferred for many hours and expedited quota shrinks (exact thresholds vary by Android version and OEM). The code is correct; the bucket is the variable.
adb shell am get-standby-bucket com.example.app adb shell am set-standby-bucket com.example.app rare # reproduce the real-user condition Also remember that vendor skins add their own aggressive battery managers on top of AOSP behavior. Treat anything an OEM-specific “optimization” screen does as a product risk to document, and avoid building features that depend on being whitelisted.
3. Battery impact data
Here is the uncomfortable truth: there is no universal number for “WorkManager costs X percent per day.” Battery cost depends on the device, the radio state, the network, the other apps on the device, and how well the system can batch your wake-ups with everyone else’s. Anyone who hands you a single figure is selling something.
What is stable is the mechanism. Energy is dominated by two things: how many times you wake the device, and how long you keep it awake once it is up. Each wake-up pays for a CPU wake, and if you touch the network it also pays for the radio’s high-power tail afterward. The API you used matters mostly because it determines how many wake-ups you create and whether the system can coalesce them.
The chart below is a model, not a measurement. It uses two stated assumptions: a 16-hour active day, and roughly half an awake-minute per wake-up (CPU plus radio tail). Radio tail length varies by carrier and modem, so treat 0.5 as a placeholder and substitute your own numbers.
Read it as a ranking of shapes, not a forecast:
- A wake lock held for the whole day dwarfs everything else. Foreground services are not expensive because they are foreground; they are expensive when they keep the CPU awake or hold a radio connection open.
- Exact alarms every few minutes are the polling anti-pattern. Each one is a guaranteed, uncoalesced wake-up.
- Periodic work is cheaper mostly because the system may batch it with other jobs. Add constraints and you give the scheduler even more freedom.
- Event-driven work is the cheapest of all, because it runs only when something actually happened.
Measure your own app
Build the habit of measuring before and after a scheduling change. A minimal loop:
adb shell dumpsys batterystats --reset # ... exercise the scenario, or leave the device idle overnight ... adb bugreport bugreport.zip # Open in Battery Historian, or capture a Perfetto trace with power rails where supported. Then check:
- Wake-up count and wake-lock time, per app, not just the headline percentage.
- Radio active time. Many small requests spread across the hour cost more than one batched request.
- Job and alarm counts in
dumpsys jobscheduleranddumpsys alarm, to confirm your schedule is the one actually running. - Standby bucket during the test, so you are not benchmarking a state real users will never be in.
In production, Android vitals reports excessive wake-ups, stuck partial wake locks, and excessive background network usage. Those are your early-warning signals; set alerts on them rather than waiting for a one-star review.
Failure-mode checklist
Paste this into your pull-request template.
- Does every worker tolerate being run twice and stopped halfway?
- Is periodic work enqueued with a unique name and a deliberate
ExistingPeriodicWorkPolicy? - Does expedited work declare an
OutOfQuotaPolicy, and doesgetForegroundInfo()exist for older API levels? - Does every foreground service declare a type, hold its permission, and avoid being started from the background?
- Is there a fallback when exact-alarm permission is missing or revoked?
- Are alarms re-armed after reboot, and does the receiver hand off immediately?
- Were the scenarios tested in the Rare bucket and under forced Doze, not only on a developer device?
- Has anyone looked at wake-up count and radio time, not just battery percentage?
The short version
Use a foreground service when the user is watching. Use an alarm when the clock matters, and let it do nothing except start something safer. Use WorkManager for everything that can wait but must not be lost. Then measure wake-ups, because that is where the battery actually goes.
Behavior described here reflects recent Android releases. Quotas, timeouts, and bucket thresholds change between versions and vary by device, so confirm specifics against the current platform documentation and on real hardware before you depend on them.
🚀 From Working Coroutines to Production-Ready Coroutines
Knowing how coroutines work is one thing. Shipping them is another: testing them deterministically, finding the concurrency bugs that get past code review, and keeping them reliable in production. I highly recommend “Kotlin Coroutines in Practice: Architecture, Testing, and Production — Volume 2 of 2.” It covers lifecycle-aware collection in the UI, architecture patterns with coroutines and Flow, testing with runTest, virtual time and Turbine, debugging and observability, performance hardening, and the library's internals. In the final chapter, everything comes together in a complete end-to-end app. Appendices A–F give you a cheat sheet, a Flow operator reference and migration guides to keep at your desk.
- E-book: Available on Google Play
- Kindle Edition: Available on Amazon
- Topmate: Available on Topmate
- Also available in Paperback & Hardcover




