Background Work
Android Development with Compose: Production & Publishing
Course 6 ยท Chapter 3 ยท Work That Outlives the Screen
Android Development with Compose: Architecture & Data 3 said coroutines in viewModelScope are right for work tied to a screen, and that work which must finish whatever the user does belongs to WorkManager. This chapter is that promise: syncing the notes in the background, even if the app is closed or the phone restarts.
OneTimeWorkRequest for one-off work and PeriodicWorkRequest for work on an interval; for Kotlin, extend CoroutineWorker rather than Worker, because it has a suspending doWork() and WorkManager cancels the coroutine when the work is stopped; constraints are set with setConstraints (network type, battery not low, charging, idle and so on); setInitialDelay on a one-time request, and for a periodic request only the first run is delayed; a periodic request can take a flex interval; requests accept backoff criteria.
Unique work: enqueueUniquePeriodicWork allows one active periodic request with a given name; REPLACE cancels the pending one and runs the new one, KEEP runs the new one only if none is pending.
Hilt: @HiltWorker with @AssistedInject and @Assisted context and WorkerParameters; the application class implements Configuration.Provider and supplies a HiltWorkerFactory.
Foreground services: from Android 14 (API 34) every foreground service needs a declared type and the matching permission besides FOREGROUND_SERVICE, otherwise MissingForegroundServiceTypeException on startForeground(); long-running workers targeting Android 14 or higher must specify a type, declared on the service element; setForeground() triggers a prerequisite check for the type; from Android 16 long-running workers can exhaust an app's job quota; WorkManager is documented for tasks under about 10 minutes and supports longer work through a foreground service.
Not found in the searches (general knowledge, not checked): the 15-minute minimum for periodic work, exact backoff behaviour, TestListenableWorkerBuilder as written, the manifest merge snippet, and the Result handling in the worker. All code is unrun (no Kotlin compiler on the machine used to write this); nothing was seen on your install.
Choosing the Right Tool
| Work | Use |
|---|---|
| Tied to a screen; fine to cancel when the user leaves | A coroutine in viewModelScope |
| Must finish even if the app is closed or the phone restarts | WorkManager (docs: persistent work) |
| Long (beyond about 10 minutes (docs)), user-visible | A foreground service, or a WorkManager worker that runs as one |
(general knowledge) WorkManager is for work that is deferrable: it will run when the conditions are right, not necessarily right now. If it must run at an exact time, it is not the tool.
A Worker for the Notes App
- (docs)
CoroutineWorkerhas a suspendingdoWork(), so the repository'ssuspendfunctions can be called directly, and the coroutine is cancelled if the work is stopped. - (general knowledge) The result tells WorkManager what to do next:
success(done),failure(do not retry) orretry(run again later, following the backoff policy). A "no connection" result is a retry; a bad response is not. - (general knowledge) A worker has no ViewModel and no screen. It gets its dependencies from the Application (manual DI, as here) or from a factory (Hilt, below).
Scheduling It
- Constraints (docs): the work waits until the network is connected and the battery is not low. The system, not you, decides when.
- Unique work (docs):
KEEPmeans callingscheduleNotesSyncon every app start does not stack up copies;REPLACEwould cancel and restart. Without a unique name you could end up with dozens of sync jobs. - Backoff: (docs) requests accept backoff criteria; (general knowledge, not checked) exponential backoff roughly doubles the wait after each retry from the starting delay.
- The interval: (general knowledge, not checked in this search) periodic work has a minimum interval of 15 minutes, so a one-hour sync is realistic and a one-minute sync is not possible. The system may also run it later than the interval; it is a "roughly hourly", not "at 10:00".
One-time work for something the user asked for:
(docs) setInitialDelay delays a one-time request; on a periodic request only the first run is delayed. ExportNotesWorker would be a second CoroutineWorker, calling Chapter 11's exportNotesAsJson from the previous course.
With Hilt
(docs) The worker class is annotated @HiltWorker, its constructor uses @AssistedInject, and the application supplies a HiltWorkerFactory through Configuration.Provider. (general knowledge) WorkManager normally creates workers itself, by reflection, with a fixed constructor; the factory is the hook that lets Hilt supply the extra arguments. Check the current docs for whether the default WorkManager initializer must be disabled in the manifest in your version; that detail was not in the search results.
Testing a Worker
(general knowledge, not checked in these searches) work-testing provides builders that create a worker directly so you can call doWork() and check the result, and a way to run the whole scheduling machinery in a test. (docs, in the first search's results) The docs also have a page on integration tests with WorkManager; read it before testing constraints and periodic timing. This is an instrumented test, like the ones in Chapter 2.
Long Work and Foreground Services (described, not built)
A sync of a few notes is short. If a worker needs to run for a long time and the user should know about it (uploading a large file, say), the docs describe two routes. The chapter describes them; the next chapter builds the notification they need.
- (docs) A long-running worker is allowed to run as a foreground service through
setForeground(). From Android 14 you must declare a type (and its permission) or the system throwsMissingForegroundServiceTypeException. - (docs) From Android 14 the system checks the type's prerequisites when you call
setForeground(); (docs) from Android 16 long-running workers can use up the app's job quota, so launching a foreground service directly is an option. - (general knowledge, not checked) The right type depends on what the work does (data sync, media, location and others); the "Foreground service types" page lists them and the permission each needs. The manifest snippet above is the shape, with the
dataSynctype as an example; confirm it against the current page and your target API. - A foreground service shows a notification. That is Chapter 4's subject, with the permission needed on newer Android versions.
Seeing What WorkManager Did
(general knowledge, not checked) The App Inspection tool in Android Studio has a Background Task Inspector that lists workers and their states, and a worker's state moves through ENQUEUED, RUNNING and SUCCEEDED (or FAILED, CANCELLED, BLOCKED). Because constraints decide when, "why has it not run?" is usually "a constraint is not met"; check the inspector before blaming the code.
CoroutineWorker with the repository from Architecture & Data, adds the unique-work and Hilt patterns, and describes the Android 14 foreground-service type rule. Alarms and classic services are not covered here.
Try It Yourself
Add SyncNotesWorker and scheduleNotesSync to the notes app. Run the app, then use the Background Task Inspector to find the job. Report its state and which constraints it was waiting on. Then change the interval to the shortest you are allowed and report what happens.
Write ExportNotesWorker as one-time work that only runs while charging. Enqueue it from a button, then plug in or unplug the emulator's charger (Extended controls) and report what you see. Then explain why REPLACE against KEEP matters for the periodic sync.
Write the worker test, then add a second test where the fake repository returns NoConnection and check the result is a retry. Say what you had to change to give the worker a fake (the worker creates its own repository from the Application).
CoroutineWorker and its cancellation; setConstraints and the constraint kinds; setInitialDelay and its periodic behaviour; flex intervals; backoff criteria existing; enqueueUniquePeriodicWork, KEEP and REPLACE; the Hilt worker pattern; the Android 14 foreground-service type rule, the exception, the prerequisite check, the Android 16 job-quota note, and the roughly-10-minutes guidance.General knowledge, not checked: the 15-minute periodic minimum; how exponential backoff grows; the
Result mapping in the worker; the manual-DI worker; the Hilt factory explanation and the manifest initializer detail; work-testing and TestListenableWorkerBuilder as written; the manifest service snippet and the dataSync choice; the Background Task Inspector and the work states; every import and the code as written.Not verified: the current WorkManager artifact and version; every listing and solution (unrun); the exercises (not run by me). Nothing was checked on your install.
Sources: Define work requests (developer.android.com), Threading in CoroutineWorker (developer.android.com), WorkManager API reference (developer.android.com), Support for long-running workers (developer.android.com), Foreground service types are required (developer.android.com), Foreground service types (developer.android.com), Integration tests with WorkManager (developer.android.com).