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?
answer
- short and urgent vs long and visible
- quota from the standby bucket
- network and storage constraints only
- notification plus service type
basics
~20 ssetExpedited 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.
solid answer
~40 sFor a quick action, like uploading one photo the user just took, I call `setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST)` on a `OneTimeWorkRequest`. It starts immediately if the app's expedited quota allows, and otherwise either runs as ordinary work or, with `DROP_WORK_REQUEST`, is dropped. `build()` rejects an expedited request that has a charging, battery or idle constraint, an initial delay, or is periodic. Below Android 12 WorkManager may run expedited work as a foreground service, so the worker must implement `getForegroundInfo()`. A whole album can take longer than ten minutes, so there I call `setForeground(ForegroundInfo(id, notification, FOREGROUND_SERVICE_TYPE_DATA_SYNC))` inside `doWork()`. The work then runs as a foreground service with an ongoing notification and a cancel action from `createCancelPendingIntent(id)`. Apps targeting Android 14 must declare that type on WorkManager's `SystemForegroundService`, and `setForeground()` can throw when a foreground start isn't allowed.
code
kotlin · 44 linesclass AlbumBackupWorker(
appContext: Context,
params: WorkerParameters,
) : CoroutineWorker(appContext, params) {
// Also used when WorkManager runs this work expedited below Android 12.
override suspend fun getForegroundInfo(): ForegroundInfo = createForegroundInfo(progress = 0)
override suspend fun doWork(): Result {
try {
setForeground(createForegroundInfo(progress = 0))
} catch (e: IllegalStateException) {
// A foreground start is not allowed right now; carry on as ordinary work.
}
uploadAlbum { percent -> setProgress(workDataOf(KEY_PROGRESS to percent)) }
return Result.success()
}
private suspend fun uploadAlbum(onProgress: suspend (Int) -> Unit) {
// Upload each photo, reporting progress through onProgress.
}
private fun createForegroundInfo(progress: Int): ForegroundInfo {
val cancel = WorkManager.getInstance(applicationContext).createCancelPendingIntent(id)
val notification = NotificationCompat.Builder(applicationContext, CHANNEL_ID)
.setContentTitle("Backing up album")
.setSmallIcon(android.R.drawable.stat_sys_upload)
.setOngoing(true)
.setProgress(100, progress, false)
.addAction(android.R.drawable.ic_delete, "Cancel", cancel)
.build()
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ForegroundInfo(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC)
} else {
ForegroundInfo(NOTIFICATION_ID, notification)
}
}
companion object {
const val CHANNEL_ID = "backup"
const val NOTIFICATION_ID = 42
const val KEY_PROGRESS = "progress"
}
}go deeper
Recall that setExpedited is for short urgent work and setForeground is for long work that shows a notification.
Explain the expedited quota and both OutOfQuotaPolicy values, and why a worker needs getForegroundInfo() when it may be expedited on older platforms.
Diagnose build-time rejections of expedited requests, the Android 14 service-type requirement and setForeground exceptions, and pick the tool per user action.
Weigh WorkManager's foreground support against the newer platform quotas and decide when a user-initiated transfer should leave WorkManager altogether.
## Two tools for two kinds of urgency WorkManager offers two ways to say "this matters to the user", and they solve different problems. - **Expedited work** (`setExpedited`, since WorkManager 2.7) asks the system to start a short job *now* rather than whenever it is convenient. It suits tasks that finish within a few minutes: sending a message, uploading one photo, completing a purchase step. - **Long-running work** (`setForeground` in a `CoroutineWorker`, `setForegroundAsync` in a `ListenableWorker`) asks the OS to keep the process alive while the worker runs. WorkManager runs a foreground service on your behalf, shows your notification, and the worker may run past the normal ten-minute limit. ## Expedited work and its quota ```kotlin val request = OneTimeWorkRequestBuilder<PhotoUploadWorker>() .setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST) .setConstraints( Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build() ) .build() ``` The system gives each app a **quota of expedited execution time**, based on its standby bucket and process importance. While the app is in the foreground the quota does not limit expedited work; it applies once the app is in the background. When the quota is spent, `OutOfQuotaPolicy` decides: | `OutOfQuotaPolicy` | Out of quota, the request | |---|---| | `RUN_AS_NON_EXPEDITED_WORK_REQUEST` | runs as ordinary deferrable work | | `DROP_WORK_REQUEST` | is cancelled | `build()` enforces the shape of expedited work with `IllegalArgumentException`s: 1. Only network and storage constraints are allowed ("Expedited jobs only support network and storage constraints"), so *unmetered Wi-Fi while charging* cannot be expedited. 2. No initial delay ("Expedited jobs cannot be delayed"). 3. No periodic requests ("PeriodicWorkRequests cannot be expedited"). A worker does not know whether it is running expedited; the request decides that, and the same worker class can be enqueued both ways. The quota is a rolling time window, so an app that spends it on a burst of expedited requests may find the next urgent request running as ordinary work, or dropped, until the quota refreshes. Treat expedited as a request for priority, not a promise, and keep the deferrable path working. On platforms **before Android 12**, WorkManager may run an expedited job as a foreground service, which needs a notification. A worker that may be expedited must therefore implement `getForegroundInfo()`; `CoroutineWorker`'s default implementation throws `IllegalStateException("Not implemented")`, which surfaces as a crash only on older devices. ## Long-running work with `setForeground` 1. Build a `ForegroundInfo(notificationId, notification, foregroundServiceType)`; give the notification a cancel action from `WorkManager.createCancelPendingIntent(id)`. 2. Call `setForeground(info)` early in `doWork()`, and again with a new `ForegroundInfo` to update progress in the notification. 3. If the app targets **Android 14 (API 34)** or higher, every long-running worker needs a foreground service type. Declare it by merging `android:foregroundServiceType` into WorkManager's `androidx.work.impl.foreground.SystemForegroundService` entry with `tools:node="merge"`, and pass the matching type at runtime. An upload is `dataSync`, which also needs the platform's `FOREGROUND_SERVICE_DATA_SYNC` permission. 4. Wrap `setForeground()` in `try`/`catch`: it throws `IllegalStateException` when the app may not start a foreground service at that moment, and on Android 12 and higher the more specific `ForegroundServiceStartNotAllowedException`. ## Choosing for "Back up now" | Situation | Tool | |---|---| | One photo the user just shot, a few seconds of upload | `setExpedited` with `RUN_AS_NON_EXPEDITED_WORK_REQUEST` | | A whole album, possibly longer than ten minutes, with visible progress | `setForeground` with a `dataSync` `ForegroundInfo` and a cancel action | | Nightly sync of anything new, on Wi-Fi while charging | ordinary constrained work, neither expedited nor foreground | ## Failure modes worth naming - Expedited jobs can still be **deferred** when system load is high or the quota is exhausted; "expedited" is not a guarantee of instant execution. - From Android 16, long-running workers, which still schedule through `JobScheduler`, can **exhaust the app's job quota**. The documentation's way out is to start a foreground service directly instead, or, for a download the user asked for, a user-initiated data transfer job, which is exempt from the ordinary job quotas. - A foreground worker can be stopped when its service type's time limit runs out; `WorkInfo.stopReason` then reports `STOP_REASON_FOREGROUND_SERVICE_TIMEOUT`, added in WorkManager 2.10. - Forgetting the service type on Android 14 or higher makes the foreground start fail at runtime, not at build time.
- Your expedited upload crashes only on an Android 11 test device; what is the likely cause?The worker does not override `getForegroundInfo()`. Below Android 12, WorkManager may run expedited work as a foreground service and asks the worker for a notification; `CoroutineWorker`'s default `getForegroundInfo()` throws `IllegalStateException("Not implemented")`. Implement it to return a `ForegroundInfo` with a notification.
- How does the user cancel a long-running WorkManager upload from its notification?Build a `PendingIntent` with `WorkManager.getInstance(context).createCancelPendingIntent(id)` and add it as a notification action. Tapping it cancels the work by ID without a custom receiver; the worker is stopped, and a `CoroutineWorker`'s coroutine is cancelled.
- An expedited request can require charging as long as it also requires Wi-Fi.
- Expedited work ignores quotas, so it always starts instantly.
- setForeground() is only needed below Android 12 and can be skipped on newer devices.
- A long-running worker needs no manifest change when the app targets Android 14.
- A periodic backup can be expedited so each run starts at once.
Assumes WorkManager 2.12; setExpedited exists since 2.7.0 and WorkInfo.STOP_REASON_FOREGROUND_SERVICE_TIMEOUT since 2.10.0.