skip to content

WorkManager

WorkManager runs deferrable work that survives process death and reboot, with constraints, chains, unique and periodic requests. Background limits make 'just start a service' wrong.

on this pageshow

explore

questions

6

In WorkManager, how do you schedule a photo upload that runs only on unmetered Wi-Fi while charging, and why not just launch a coroutine?

level: juniorimportance: must knowfreq 78%

answer

  1. persisted, not in-memory
  2. worker, request, enqueue
  3. Constraints.Builder on the request
  4. success, retry or failure

basics

~10 s

Subclass CoroutineWorker, build a OneTimeWorkRequest whose Constraints require NetworkType.UNMETERED and charging, and enqueue it. WorkManager persists the request, so it survives process death and reboot; a plain coroutine dies with the process.

solid answer

~40 s

I write a `CoroutineWorker` whose `doWork()` uploads the photo and returns `Result.success()`, `Result.retry()` or `Result.failure()`. I build `OneTimeWorkRequestBuilder<PhotoUploadWorker>()` with `Constraints.Builder().setRequiredNetworkType(NetworkType.UNMETERED).setRequiresCharging(true).build()`, pass the photo's URI as input `Data`, and call `WorkManager.getInstance(context).enqueue(request)`. WorkManager stores the request in its own database and schedules it with the OS, so the upload still happens after the user leaves the app, the process is killed or the phone reboots. A coroutine launched from a ViewModel or an application scope lives only as long as the process and knows nothing about Wi-Fi or charging. If a constraint stops holding mid-run, WorkManager stops the worker and runs it again once every constraint is met.

code

kotlin · 37 lines
kotlin
class PhotoUploadWorker(
    appContext: Context,
    params: WorkerParameters,
) : CoroutineWorker(appContext, params) {

    override suspend fun doWork(): Result {
        val uri = inputData.getString(KEY_PHOTO_URI) ?: return Result.failure()
        return try {
            uploadPhoto(uri)
            Result.success()
        } catch (e: IOException) {
            Result.retry()
        }
    }

    private suspend fun uploadPhoto(uri: String) {
        // Suspending network call that sends the photo at this URI.
    }

    companion object {
        const val KEY_PHOTO_URI = "photo_uri"
    }
}

fun schedulePhotoUpload(context: Context, photoUri: String) {
    val constraints = Constraints.Builder()
        .setRequiredNetworkType(NetworkType.UNMETERED)
        .setRequiresCharging(true)
        .build()

    val request = OneTimeWorkRequestBuilder<PhotoUploadWorker>()
        .setConstraints(constraints)
        .setInputData(workDataOf(PhotoUploadWorker.KEY_PHOTO_URI to photoUri))
        .build()

    WorkManager.getInstance(context).enqueue(request)
}

go deeper

for a junior

Recall the three pieces: a worker class, a request with Constraints attached, and enqueue(). Know what success, retry and failure each lead to.

for a middle

Explain that WorkManager persists each request in its own database and schedules it with the OS, which is why the work outlives the process, and what happens when a constraint is lost mid-run.

for a senior

Show production habits: make doWork idempotent because a run can be stopped and repeated, return retry only for transient errors, and respect the ten-minute execution window.

for a principal

Position WorkManager as the team's single path for work that must finish without the user watching, and be clear about what stays in screen-scoped coroutines.

## Why WorkManager instead of a coroutine A **coroutine** launched from a ViewModel, a lifecycle scope or an application-wide scope lives inside the app process. When the user swipes the app away and the system reclaims the process, or when the phone reboots, the coroutine is gone and nothing remembers that an upload was pending. It also has no built-in way to wait for an unmetered network or a charger. **WorkManager** is the Jetpack library for *deferrable, guaranteed* background work. When you call `enqueue()`, it writes the request into an internally managed SQLite database and schedules it with the operating system's job scheduler. WorkManager's own manifest registers a receiver for the boot-completed broadcast, so pending work is rescheduled after a reboot, and when the work becomes eligible WorkManager starts your worker even if the app process had to be started for it. ## The three pieces you write 1. **A worker.** `Worker` has a synchronous `doWork()` that WorkManager calls on a background executor. In Kotlin you normally extend `CoroutineWorker`, whose `doWork()` is a `suspend` function that runs on `Dispatchers.Default` unless the WorkManager configuration says otherwise. 2. **A request.** `OneTimeWorkRequestBuilder<PhotoUploadWorker>()` creates a `OneTimeWorkRequest`. On the builder you attach `setConstraints(...)`, `setInputData(...)`, `addTag(...)` or `setInitialDelay(...)`. 3. **Enqueueing.** `WorkManager.getInstance(context).enqueue(request)` hands it over. Each request gets a `UUID` `id` you can use to observe or cancel it. ```kotlin val constraints = Constraints.Builder() .setRequiredNetworkType(NetworkType.UNMETERED) .setRequiresCharging(true) .build() val request = OneTimeWorkRequestBuilder<PhotoUploadWorker>() .setConstraints(constraints) .setInputData(workDataOf("photo_uri" to uri.toString())) .build() WorkManager.getInstance(context).enqueue(request) ``` ## The constraints on offer | `Constraints.Builder` method | The work waits until | |---|---| | `setRequiredNetworkType(NetworkType.UNMETERED)` | an unmetered network, such as typical Wi-Fi, is available | | `setRequiresCharging(true)` | the device is charging | | `setRequiresBatteryNotLow(true)` | the device is not in low-battery mode | | `setRequiresStorageNotLow(true)` | storage is not low | | `setRequiresDeviceIdle(true)` | the device is idle | `NetworkType` also offers `NOT_REQUIRED`, `CONNECTED`, `NOT_ROAMING` and `METERED`. When several constraints are set, **all** of them must hold. If one stops holding while the worker runs, for example the phone leaves Wi-Fi, WorkManager **stops the worker** and runs it again once every constraint is met, so the upload has to be safe to start over. ## What `doWork()` returns | Return value | Resulting state | What happens next | |---|---|---| | `Result.success()` (optionally with output `Data`) | `SUCCEEDED` | dependent work in a chain is unblocked | | `Result.retry()` | back to `ENQUEUED` | rerun after a backoff delay; the default is `BackoffPolicy.EXPONENTIAL` starting at 30 seconds | | `Result.failure()` | `FAILED` | no automatic retry; dependent work fails too | An exception that escapes `doWork()` is treated like a failure, so catch the transient errors (a dropped connection) and turn them into `Result.retry()`, and keep `Result.failure()` for errors that will never fix themselves, such as a photo that no longer exists. ## Following the result `enqueue()` returns at once; the upload happens later, possibly in another process. To show its status, observe the request by its ID: `WorkManager.getInstance(context).getWorkInfoByIdFlow(request.id)` emits a `WorkInfo` whose `state` moves from `ENQUEUED` (waiting for Wi-Fi and a charger) to `RUNNING` and then to `SUCCEEDED` or `FAILED`. Because the request lives in WorkManager's database, a screen opened after a process restart can still find it, which a coroutine's result never could. ## Limits a junior engineer should still know - **Not exact timing.** WorkManager guarantees the work runs once its conditions are met, not at a precise moment; the OS batches and defers jobs to save battery. - **A ten-minute window.** A worker is given a maximum of ten minutes to return a result; past that the system stops it and the work is retried later. Longer user-visible work uses `setForeground()`. - **Small inputs.** Input and output `Data` is limited to 10 KB when serialized, so pass a URI or a database ID, never the photo bytes. - **Idempotent work.** Because a run can be stopped and repeated, an upload should be safe to send twice, for instance by letting the server deduplicate on a photo ID. - **Use the `Context` overload.** Always call `WorkManager.getInstance(context)`; the no-argument `getInstance()` is deprecated and throws if WorkManager has not been initialized yet. The short version for an interview: a coroutine is the right tool for work tied to a screen; WorkManager is the right tool for work that must finish even if the user never opens the app again.

  • What does Result.retry() do, and how long does WorkManager wait before the next attempt?
    The work goes back to `ENQUEUED` and is rescheduled after a backoff delay. By default the policy is `BackoffPolicy.EXPONENTIAL` starting at 30 seconds, so roughly 30, 60, 120 seconds, capped at five hours. `setBackoffCriteria()` changes the policy (`LINEAR` or `EXPONENTIAL`) and the starting delay, which WorkManager clamps to at least 10 seconds. The constraints still have to hold before the retry runs.
  • Which thread does a CoroutineWorker's doWork() run on, and how is that different from a Worker?
    A `Worker`'s blocking `doWork()` runs on the background `Executor` from WorkManager's `Configuration`. A `CoroutineWorker`'s suspending `doWork()` runs on `Dispatchers.Default` unless the configuration sets `setWorkerCoroutineContext()` or `setExecutor()`; for blocking I/O you switch with `withContext(Dispatchers.IO)` inside `doWork()`. Neither runs on the main thread, and a stopped `CoroutineWorker` is cancelled like any coroutine.

  • A coroutine in an application-wide scope is as reliable as WorkManager for uploads.
  • Constraints are only checked once, at the moment enqueue() is called.
  • Worker.doWork() runs on the main thread, so the upload must start its own thread.
  • Returning Result.failure() makes WorkManager try the work again later.
  • Enqueued work is lost when the phone reboots.
open as a page

In WorkManager, how do you run compress-then-upload as one unique chain, pass Data between the steps, and observe it from the UI?

level: middleimportance: must knowfreq 62%

basics

~10 s

Call beginUniqueWork(name, ExistingWorkPolicy, compress).then(upload).enqueue(); each step's output Data, at most 10 KB, becomes the next step's input. Observe the chain with getWorkInfosForUniqueWorkFlow(name), which emits every step's WorkInfo.

open as a page

In WorkManager, when the user taps Back up now on a large album, when do you use setExpedited with an OutOfQuotaPolicy, and when setForeground with ForegroundInfo?

level: seniorimportance: should knowfreq 48%

basics

~20 s

setExpedited suits short, user-important work that must start now; it uses a system quota and allows only network and storage constraints. setForeground runs a worker as a foreground service with a notification, for user-visible work that may exceed ten minutes.

open as a page

In WorkManager, a nightly cleanup runs as unique periodic work; how do the 15-minute floor, the flex interval and ExistingPeriodicWorkPolicy decide when it runs and which version runs?

level: seniorimportance: should knowfreq 52%

basics

~20 s

PeriodicWorkRequest clamps intervals under 15 minutes to 15 with a log warning, and a flexInterval of at least 5 minutes confines runs to the end of each period. ExistingPeriodicWorkPolicy.UPDATE applies a new spec without resetting the schedule; KEEP keeps the old one.

open as a page

In WorkManager without Hilt, how do you give a worker constructor dependencies through a custom WorkerFactory, and how do you test that worker?

level: seniorimportance: should knowfreq 38%

basics

~10 s

Subclass WorkerFactory, build your worker in createWorker (return null to fall back to the default), set it with Configuration.Builder.setWorkerFactory from an Application implementing Configuration.Provider, and remove WorkManagerInitializer from the manifest. Test with TestListenableWorkerBuilder.setWorkerFactory.

open as a page

As Android lead, what rule do you set for which work goes to WorkManager, which stays in a coroutine, and which becomes a user-visible transfer?

level: principalimportance: should knowfreq 32%

basics

~20 s

Work that must finish after the user leaves goes to WorkManager as unique, idempotent requests; work only the open screen needs stays in a scoped coroutine. Long transfers the user watches use setForeground, or a platform user-initiated transfer under quota pressure.

open as a page