Lesson 6 of 9 · 29m
WorkManager and Android's Background Execution Reality
Choose correct primitives for deferrable, exact, expedited, and foreground work while respecting Doze, battery, and vendor behavior.
Android background execution is where optimistic architecture goes to be educated. The platform restricts work because every app believes its sync is important, and the battery pays for their collective enthusiasm. Your job is not to defeat the constraints. It is to classify work correctly: does it need to happen eventually, soon, exactly now, or while the user can see it?
WorkManager is for guaranteed deferrable work
If work must survive app exit, reboot, or process death but does not require exact timing, use WorkManager:
val upload = OneTimeWorkRequestBuilder<PhotoUploadWorker>()
.setConstraints(
Constraints.Builder()
.setRequiredNetworkType(NetworkType.UNMETERED)
.setRequiresBatteryNotLow(true)
.build()
)
.setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS)
.build()
WorkManager.getInstance(context).enqueueUniqueWork(
"photo-upload-42",
ExistingWorkPolicy.REPLACE,
upload,
)Unique work names and policies are architectural decisions. REPLACE is right for a new draft upload, wrong for unrelated uploads sharing the same name.
Workers must be idempotent and timeout-aware
A worker can retry, run after reboot, or be interrupted. Treat input as durable instructions and re-check state:
class PhotoUploadWorker(ctx: Context, params: WorkerParameters) : CoroutineWorker(ctx, params) {
override suspend fun doWork(): Result {
val id = inputData.getString("photo_id") ?: return Result.failure()
return when (uploader.uploadIfPending(id)) {
UploadOutcome.Done -> Result.success()
UploadOutcome.RetryLater -> if (runAttemptCount < 5) Result.retry() else Result.failure()
UploadOutcome.Invalid -> Result.failure()
}
}
}Do not assume a successful enqueue means the network call started once. It may start multiple times across retries unless the backend or local state deduplicates it.
Exact alarms are not a scheduler for everything
Exact alarms are for user-visible timing: medication reminders, calendar alarms, clock behavior. They are restricted because apps abused them as polling loops. For periodic sync, accept inexactness. For urgent user-initiated work, consider expedited work; quota and platform conditions still apply. If the user is actively waiting and the task must continue for minutes, a foreground service with a visible notification may be appropriate — and only for the service type the platform permits.
Vendor reality matters
Pixel behavior is not the whole Android ecosystem. Some manufacturers aggressively kill processes, delay jobs, or require users to enable "autostart" and battery exemptions. You cannot code your way around every OEM fork. You can design for graceful recovery: durable queue state, reconciliation on next launch, exponential backoff, and honest UI that says sync is pending instead of pretending completion.
Observe work instead of hoping
Expose work state through WorkInfo and tests:
WorkManager.getInstance(context)
.getWorkInfosForUniqueWorkFlow("photo-upload-42")
.map { infos -> infos.firstOrNull()?.state }Instrument enqueue counts, retry counts, failure causes, and last successful sync. "Background sync sometimes doesn't happen" is not diagnosable without telemetry.
Field notes
- WorkManager is not a realtime messaging system; use push or direct foreground interaction when latency matters.
- Periodic work has minimum intervals and will be shifted for battery health.
- A foreground service is a contract with the user: visible notification, meaningful task, stop promptly.
- Test airplane mode, metered network, low battery, reboot, app update, and process death between enqueue and execution.
- Do not request battery optimization exemptions as a shortcut; Play policy and user trust both notice.
Was this lesson helpful?