WorkManager

Learn Android WorkManager to master scheduling, constraints, and Hilt integration while understanding when to use it over coroutines or services. About 25 minutes.

Why it matters

  • WorkManager is the Jetpack API for persistent background work: work you enqueue is stored in a database, survives app restarts and reboots, and respects Doze and App Standby.
  • Picking the wrong unique-work policy (for example cancelling a running sync on every app start) is a common cause of "sync never completes" bugs.
  • The 10 KB Data limit, the 15-minute periodic minimum and the 10-minute execution window are hard limits that break code ported from a raw coroutine or a service.
  • Interviews probe whether you know when WorkManager is the wrong tool, and how expedited work behaves on Android 12+ versus older versions.

The simple explanation

  • A work order at a warehouse: you hand in a ticket saying "sync the inventory, but only when a truck is docked (network) and the forklift is charged (battery not low)."
  • The system files the ticket and runs it when conditions are met, even if the office closed and reopened (reboot); you do not stand by the forklift.
  • If loading fails, the ticket goes back in the pile with a backoff delay that grows each time.
  • A unique-work name is a ticket number: you decide whether a second "sync" ticket is ignored, replaces the first, or waits behind it.

WorkManager runs work that must complete even if the user leaves the app or the device restarts: syncing, uploading logs, backing up. It is not for work that only matters while a screen is open (use a coroutine in viewModelScope) or for an exact clock time (use an alarm).

Core pieces

  • A worker: CoroutineWorker (recommended in Kotlin) with suspend fun doWork(): Result. It runs on Dispatchers.Default by default; Room and Retrofit suspend calls are already main-safe.
  • A request: OneTimeWorkRequestBuilder<W>() or PeriodicWorkRequestBuilder<W>(repeatInterval, unit). The periodic minimum is 15 minutes; smaller values are raised to 15 minutes with a log warning. An optional flex interval (at least 5 minutes) lets the work run anywhere in the last part of each period.
  • Constraints: setRequiredNetworkType(NetworkType.CONNECTED), setRequiresBatteryNotLow, setRequiresCharging, setRequiresStorageNotLow, setRequiresDeviceIdle.
  • The result: Result.success(outputData), Result.retry() (try again after the backoff delay) or Result.failure() (stop; dependent work in a chain fails too).

Backoff. setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS) sets the policy and initial delay. The default is exponential with 30 seconds, the minimum delay is 10 seconds, and the delay is capped at 5 hours. Exponential gives 30 s, 60 s, 120 s...; linear gives 30 s, 60 s, 90 s...

Unique work. enqueueUniqueWork(name, ExistingWorkPolicy, request) for one-time work, with KEEP (ignore the new request if unfinished work exists), REPLACE (cancel the existing work, including a running one, and enqueue the new one), APPEND (run after the existing work; if that fails, the new work fails too) and APPEND_OR_REPLACE (like APPEND, but starts a fresh chain if the existing one failed). Periodic work uses enqueueUniquePeriodicWork with ExistingPeriodicWorkPolicy: KEEP, UPDATE (apply the new request's settings without cancelling a running worker) or CANCEL_AND_REENQUEUE.

Chaining. beginWith(a).then(b).enqueue() runs b after a succeeds; beginWith(listOf(a, b)).then(c) runs a and b in parallel, then c, which receives their merged output data. beginUniqueWork(...) makes the whole chain unique.

Data. Input and output are Data key-value pairs (workDataOf("id" to 42)), limited to 10 KB (10,240 bytes) serialized. Building a larger Data throws. Pass an id or a file URI and load the payload in the worker.

Expedited work. setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST) asks for important, short work to start as soon as possible, subject to a per-app quota. Only one-time work can be expedited. On Android 12+ it runs as an expedited job; on older versions WorkManager runs it as a foreground service, so the worker must override getForegroundInfo() to supply a notification.

Observing. getWorkInfosForUniqueWorkFlow(name) and getWorkInfoByIdFlow(id) return a Flow of WorkInfo with the state (ENQUEUED, RUNNING, SUCCEEDED, FAILED, BLOCKED, CANCELLED), progress and output.

ConceptKey fact
Periodic minimum15 minutes (flex at least 5 minutes)
Default backoffExponential, 30 s initial, 10 s minimum, 5 h cap
One-time unique policiesKEEP, REPLACE, APPEND, APPEND_OR_REPLACE
Periodic unique policiesKEEP, UPDATE, CANCEL_AND_REENQUEUE
Data limit10 KB per input or output
One runAbout 10 minutes before the system stops the worker
Expedited before Android 12Runs as a foreground service; needs getForegroundInfo()
The states of a work request
The states of a work request A work request starts ENQUEUED, or BLOCKED until earlier work finishes; it runs when its constraints are met, then Result.success() makes it SUCCEEDED, Result.failure() makes it FAILED, and Result.retry() or lost constraints put it back to ENQUEUED; cancelling an enqueued or running request makes it CANCELLED. EARLIER WORK DONE CONSTRAINTS MET retry() OR CONSTRAINTS LOST cancel() cancel() success() failure() BLOCKED waits for earlier work ENQUEUED waits for constraints RUNNING doWork() runs SUCCEEDED final FAILED final CANCELLED final
Result.retry() sends the work back to ENQUEUED after the backoff delay; SUCCEEDED, FAILED and CANCELLED are final.

Notes

  • Choose by guarantee: a coroutine in viewModelScope for work tied to a screen, WorkManager for deferrable work that must finish, a foreground service for long user-visible work that must run now (playback, navigation), an alarm for an exact time.
  • Periodic work cannot run more often than every 15 minutes, and it runs at some point in each interval, not at a fixed clock time.
  • Each run gets about 10 minutes. Longer work should be split into a chain, or call setForeground() to run as a foreground service (on Android 14+ declare the matching foregroundServiceType for WorkManager's SystemForegroundService in your manifest).
  • Result.retry() applies the backoff; Result.failure() stops the work and fails any work chained after it. Check runAttemptCount to give up after a few attempts.
  • CoroutineWorker is cancelled when constraints stop being met or the work is cancelled; the coroutine gets a CancellationException, so do not swallow it in a broad catch.
  • For periodic sync started at every app launch, use ExistingPeriodicWorkPolicy.KEEP; use UPDATE when you change its constraints or interval in a new release.
  • Pass ids or URIs in Data, not payloads; the 10 KB limit applies to each input and output.
  • @HiltWorker needs androidx.hilt:hilt-work, ksp("androidx.hilt:hilt-compiler"), an Application that implements Configuration.Provider with the injected HiltWorkerFactory, and the default WorkManagerInitializer removed from the manifest.
  • Without Hilt, inject dependencies with your own WorkerFactory set in Configuration; do not try to pass objects through Data.
  • Test workers with work-testing: TestListenableWorkerBuilder runs one worker directly, and WorkManagerTestInitHelper gives a synchronous WorkManager for testing enqueue logic and constraints.

Code example

A @HiltWorker that syncs with network and battery constraints, exponential backoff and a give-up limit, scheduled as unique periodic work, plus the Application setup Hilt needs and a Flow to observe it.

// SyncWorker.kt
import android.content.Context
import androidx.hilt.work.HiltWorker
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import dagger.assisted.Assisted
import dagger.assisted.AssistedInject
import retrofit2.HttpException
import java.io.IOException
 
interface SyncRepository {
    suspend fun sync() // Room + Retrofit suspend calls inside, already main-safe
}
 
@HiltWorker
class SyncWorker @AssistedInject constructor(
    @Assisted appContext: Context,
    @Assisted params: WorkerParameters,
    private val repository: SyncRepository, // from the Hilt graph
) : CoroutineWorker(appContext, params) {
 
    override suspend fun doWork(): Result = try {
        repository.sync()
        Result.success()
    } catch (e: IOException) {
        // Transient: try again later, but not forever
        if (runAttemptCount < MAX_ATTEMPTS) Result.retry() else Result.failure()
    } catch (e: HttpException) {
        if (e.code() >= 500 && runAttemptCount < MAX_ATTEMPTS) Result.retry() else Result.failure()
    }
 
    companion object {
        const val UNIQUE_NAME = "sync"
        private const val MAX_ATTEMPTS = 5
    }
}
 
// SyncScheduler.kt
import androidx.work.BackoffPolicy
import androidx.work.Constraints
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.NetworkType
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkInfo
import androidx.work.WorkManager
import java.util.concurrent.TimeUnit
import kotlinx.coroutines.flow.Flow
 
fun scheduleSync(workManager: WorkManager) {
    val request = PeriodicWorkRequestBuilder<SyncWorker>(1, TimeUnit.HOURS)
        .setConstraints(
            Constraints.Builder()
                .setRequiredNetworkType(NetworkType.CONNECTED)
                .setRequiresBatteryNotLow(true)
                .build()
        )
        .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS)
        .build()
 
    workManager.enqueueUniquePeriodicWork(
        SyncWorker.UNIQUE_NAME,
        ExistingPeriodicWorkPolicy.KEEP, // calling this on every launch is a no-op
        request,
    )
}
 
fun observeSync(workManager: WorkManager): Flow<List<WorkInfo>> =
    workManager.getWorkInfosForUniqueWorkFlow(SyncWorker.UNIQUE_NAME)
 
// App.kt
import android.app.Application
import androidx.hilt.work.HiltWorkerFactory
import androidx.work.Configuration
import dagger.hilt.android.HiltAndroidApp
import javax.inject.Inject
 
@HiltAndroidApp
class App : Application(), Configuration.Provider {
    @Inject lateinit var workerFactory: HiltWorkerFactory
 
    override val workManagerConfiguration: Configuration
        get() = Configuration.Builder()
            .setWorkerFactory(workerFactory)
            .build()
 
    override fun onCreate() {
        super.onCreate()
        scheduleSync(WorkManager.getInstance(this))
    }
}
<!-- AndroidManifest.xml: turn off the default initializer so WorkManager uses App's configuration -->
<provider
    android:name="androidx.startup.InitializationProvider"
    android:authorities="${applicationId}.androidx-startup"
    android:exported="false"
    tools:node="merge">
    <meta-data
        android:name="androidx.work.WorkManagerInitializer"
        android:value="androidx.startup"
        tools:node="remove" />
</provider>
  • @HiltWorker with @AssistedInject lets Hilt supply SyncRepository, while WorkManager supplies the Context and WorkerParameters. If the Configuration.Provider or the manifest change is missing, WorkManager uses its default factory, which cannot build this constructor, and every run fails at runtime even though the app compiles.
  • ExistingPeriodicWorkPolicy.KEEP makes scheduling idempotent: calling scheduleSync on every launch keeps the existing schedule instead of restarting it.
  • Only transient errors return retry(), and runAttemptCount stops the retries after five attempts; a 4xx response is a failure, not a reason to retry.
  • observeSync gives a Flow the ViewModel can turn into UI state, for example a "last synced" label or an error banner.

Run the idea in plain Kotlin

A model of how WorkManager computes retry delays and how KEEP and REPLACE treat a second request with the same unique name. It uses WorkManager's formulas (exponential: initial × 2^(attempt − 1), linear: initial × attempt, capped at 5 hours) but no real waiting.

enum class Backoff { EXPONENTIAL, LINEAR }
enum class Policy { KEEP, REPLACE }

const val MAX_BACKOFF_MS = 5L * 60 * 60 * 1000 // 5 hours

// runAttemptCount is 1 for the first retry, 2 for the second, ...
fun backoffDelayMs(policy: Backoff, initialMs: Long, runAttemptCount: Int): Long {
  val delay = when (policy) {
      Backoff.EXPONENTIAL -> initialMs * (1L shl (runAttemptCount - 1))
      Backoff.LINEAR -> initialMs * runAttemptCount
  }
  return minOf(delay, MAX_BACKOFF_MS)
}

class FakeWorkManager {
  private val unique = mutableMapOf<String, String>()
  fun enqueueUnique(name: String, policy: Policy, requestId: String) {
      val existing = unique[name]
      when {
          existing == null -> { unique[name] = requestId; println("  enqueued " + requestId) }
          policy == Policy.KEEP -> println("  KEEP: " + existing + " stays, " + requestId + " ignored")
          else -> { unique[name] = requestId; println("  REPLACE: " + existing + " cancelled, " + requestId + " enqueued") }
      }
  }
}

fun main() {
  for (policy in Backoff.values()) {
      val delays = (1..4).map { backoffDelayMs(policy, 30_000, it) / 1000 }
      println(policy.name + " retries after (s): " + delays)
  }
  println("EXPONENTIAL attempt 20 is capped at (h): " + backoffDelayMs(Backoff.EXPONENTIAL, 30_000, 20) / 3_600_000)

  println("App launched three times with KEEP:")
  val keep = FakeWorkManager()
  listOf("sync-1", "sync-2", "sync-3").forEach { keep.enqueueUnique("sync", Policy.KEEP, it) }

  println("App launched three times with REPLACE:")
  val replace = FakeWorkManager()
  listOf("sync-1", "sync-2", "sync-3").forEach { replace.enqueueUnique("sync", Policy.REPLACE, it) }
}

Expected output:

EXPONENTIAL retries after (s): [30, 60, 120, 240]
LINEAR retries after (s): [30, 60, 90, 120]
EXPONENTIAL attempt 20 is capped at (h): 5
App launched three times with KEEP:
  enqueued sync-1
  KEEP: sync-1 stays, sync-2 ignored
  KEEP: sync-1 stays, sync-3 ignored
App launched three times with REPLACE:
  enqueued sync-1
  REPLACE: sync-1 cancelled, sync-2 enqueued
  REPLACE: sync-2 cancelled, sync-3 enqueued

In production

Sync stopped after every reboot
  • A news app scheduled its 30-minute background refresh with AlarmManager and a BroadcastReceiver that started the network call.
  • Support tickets said the feed was hours old after users restarted their phones. Alarms are cleared on reboot and the app had no BOOT_COMPLETED handling, so nothing rescheduled the refresh until the app was opened.
  • When a refresh failed on a bad connection, nothing retried it, and there was no record of whether it had run at all.
The fix
  • They replaced the alarm with a unique PeriodicWorkRequest (30 minutes, NetworkType.CONNECTED, ExistingPeriodicWorkPolicy.KEEP) enqueued from Application.onCreate(). WorkManager persists it and reschedules it after a reboot.
  • The worker returns Result.retry() on IOException, so a failed refresh is retried with exponential backoff instead of waiting for the next period.
  • They checked the schedule with Android Studio's Background Task Inspector and adb shell dumpsys jobscheduler, including after a reboot, and logged WorkInfo failures to analytics.
Uploads cancelled on every app start
  • A logistics app enqueued a one-time photo upload with enqueueUniqueWork("upload", ExistingWorkPolicy.REPLACE, request) from MainActivity.onCreate().
  • Drivers opened the app many times a day. Each launch cancelled the running upload and started a new one from the beginning, which also reset its retry count and backoff.
  • On slow networks the upload never finished; the server saw a steady stream of partial uploads.
The fix
  • They changed the policy to ExistingWorkPolicy.KEEP, so a launch while an upload is pending or running does nothing. New photos are queued with APPEND_OR_REPLACE on a separate unique chain.
  • They moved the call into the repository that creates the photo record, so it runs when there is something to upload, not on every launch.
  • A test with WorkManagerTestInitHelper enqueues the upload twice and asserts that getWorkInfosForUniqueWork("upload") contains one request, still in its first attempt.

Common mistakes

  • Restarting unique work on every launch. ExistingWorkPolicy.REPLACE or ExistingPeriodicWorkPolicy.CANCEL_AND_REENQUEUE cancels running work each time. Use KEEP for scheduling that runs at startup, and UPDATE to change a periodic request's settings.
  • Passing ExistingWorkPolicy to enqueueUniquePeriodicWork. Periodic work takes ExistingPeriodicWorkPolicy; the one-time enum does not compile there.
  • Putting large payloads in Data. Building a Data over 10 KB throws. Store the payload in Room or a file and pass its id or URI.
  • Expecting a 1-minute periodic interval. WorkManager raises any interval below 15 minutes to 15 minutes, and periodic work never runs at an exact time. Use an exact alarm only when the user needs a precise time.
  • Retrying everything, forever. Result.retry() on a 400 or 401 just repeats a request that cannot succeed. Retry transient errors only and stop after a few runAttemptCount values.
  • Expedited work without getForegroundInfo(). On Android 11 and lower, expedited work runs as a foreground service, and a worker that does not override getForegroundInfo() fails there, even though it works on Android 12+.
  • @HiltWorker without the WorkManager configuration. Without Configuration.Provider with HiltWorkerFactory and the default initializer removed, WorkManager cannot construct the worker and each run fails at runtime.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“When would you choose WorkManager over a coroutine, a foreground service or an alarm?”

“Explain the unique-work policies and when you would use each.”

“How does backoff work in WorkManager?”

“What are the Data size limit and expedited work, and what traps do they hide?”

Quiz

You build a PeriodicWorkRequest with a 5-minute interval. What happens?

What is the size limit for a single input or output Data object?

A periodic sync is enqueued from Application.onCreate() on every launch. Which policy keeps the existing schedule untouched?

An expedited CoroutineWorker works on Android 13 but fails on Android 10. What is the most likely cause?

0 of 4 answered

Mini task

15-minute exercise: add a periodic sync worker with constraints and backoff

  1. Add the dependencies. In the app module: implementation("androidx.work:work-runtime-ktx:2.12.0"), implementation("androidx.hilt:hilt-work:1.4.0") and ksp("androidx.hilt:hilt-compiler:1.4.0"), in a project that already uses Hilt with KSP.

  2. Create the worker. SyncWorker annotated @HiltWorker, with an @AssistedInject constructor taking @Assisted Context, @Assisted WorkerParameters and a SyncRepository. In doWork(), call repository.sync(); return Result.retry() on IOException while runAttemptCount < 5, otherwise Result.failure().

  3. Wire WorkManager to Hilt. Make the Application implement Configuration.Provider with an injected HiltWorkerFactory, and remove androidx.work.WorkManagerInitializer from the manifest with tools:node="remove".

  4. Schedule the work. In Application.onCreate(), build PeriodicWorkRequestBuilder<SyncWorker>(1, TimeUnit.HOURS) with NetworkType.CONNECTED and setRequiresBatteryNotLow(true) constraints and setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS). Enqueue it with enqueueUniquePeriodicWork("sync", ExistingPeriodicWorkPolicy.KEEP, request).

  5. Verify. Open Android Studio's Background Task Inspector and confirm one sync work in ENQUEUED. Relaunch the app three times and confirm it is still one request with the same id. Make the fake repository throw IOException and watch the next attempt scheduled about 30 s, then 60 s, later.

  6. Break it on purpose. Switch to ExistingPeriodicWorkPolicy.CANCEL_AND_REENQUEUE, relaunch three times, and see a new request id each time. Switch back to KEEP.

Done condition: the inspector shows a single periodic sync request across relaunches, failed runs are retried with growing delays and stop after five attempts, and the worker is created through Hilt (no WorkerFactory "could not instantiate" error in logcat).

Next: Foreground services