Background processing is essential for Android applications that need to synchronize data, upload files, send analytics, or complete operations when the user is not actively using the app. WorkManager provides a reliable way to schedule deferrable background work while respecting Android's battery and execution restrictions.
A common mistake in Android development is using a background thread or service for every task. These approaches may work while the application is running, but they do not automatically guarantee that the task will continue after the process is killed, the device restarts, or network connectivity changes.
WorkManager solves this problem by providing a persistent task scheduling API. Developers can define what work needs to happen, specify the conditions under which it can run, and let Android decide when resources are available.
This article explains how WorkManager operates, how to implement background synchronization using Kotlin, and how to handle retries, constraints, duplicate requests, and long-running tasks in production applications.
What Is WorkManager?
WorkManager is part of Android Jetpack and is the recommended solution for persistent background work that should continue even when the application leaves the foreground.
It is useful for tasks such as:
- Uploading images and documents.
- Synchronizing application data with a server.
- Processing locally stored records.
- Sending analytics events.
- Downloading files when network conditions allow.
- Running periodic maintenance operations.
WorkManager stores scheduled work in an internal database and coordinates execution with Android's scheduling mechanisms. On modern Android versions, it uses JobScheduler to schedule work.
This persistence is important. If Android terminates the application process, WorkManager can reschedule eligible work when the application or device becomes available again.
However, WorkManager does not guarantee execution at an exact time. The operating system controls scheduling based on constraints, battery conditions, system load, and execution quotas.
For example, if an application schedules a synchronization task to run every 30 minutes, it should not assume that the task will execute at precisely 30-minute intervals.
Understanding the Types of Background Work
WorkManager supports different execution patterns depending on the application's requirements.
One-time work
One-time work executes a task once. It is useful for uploading a document, submitting a form, or synchronizing data after a user performs an action.
For example, when a user updates their profile, the application can enqueue a one-time worker to upload the updated information.
Periodic work
Periodic work runs repeatedly according to a defined interval. It is useful for background synchronization, data cleanup, and scheduled maintenance.
The minimum repeat interval for periodic WorkManager requests is 15 minutes. Even when a longer interval is configured, the actual execution time remains controlled by Android.
Expedited work
Expedited work is designed for short, important tasks that should begin as soon as possible.
For example, an application may use expedited work to send a user-requested update after the user leaves the screen.
Expedited work is still subject to system quotas. If the application exceeds its available quota, the developer can choose whether the request should fall back to ordinary work or be dropped.
Long-running work
WorkManager can support operations that take longer than the normal worker execution window, such as large uploads or downloads.
For these operations, a worker can run as a foreground service with a visible notification. This does not remove Android's foreground-service restrictions or job scheduling limits.
Setting Up WorkManager in an Android Project
WorkManager can be added through the module-level Gradle configuration.
For a Kotlin application using coroutine workers, add the WorkManager KTX dependency:
dependencies {
implementation("androidx.work:work-runtime-ktx:<version>")
}
Replace the version placeholder with the stable version selected for your project.
The KTX dependency provides Kotlin-friendly APIs, including CoroutineWorker, which makes it easier to implement asynchronous work using suspend functions.
Creating Your First Background Worker
Let's build a practical example.
Assume an application stores user activity records locally and needs to upload pending records to a backend API whenever network connectivity is available.
The worker will:
- Retrieve pending records from local storage.
- Send the records to the backend.
- Mark successfully uploaded records as synchronized.
- Retry temporary failures.
- Stop processing when the operation cannot be recovered automatically.
Step 1: Create a CoroutineWorker
Create a class named ActivitySyncWorker.
class ActivitySyncWorker(
appContext: Context,
workerParams: WorkerParameters
) : CoroutineWorker(appContext, workerParams) {
override suspend fun doWork(): Result {
return try {
val repository = ActivityRepository(
applicationContext
)
val pendingRecords =
repository.getPendingRecords()
if (pendingRecords.isEmpty()) {
return Result.success()
}
val response =
repository.uploadRecords(pendingRecords)
if (response.isSuccessful) {
repository.markAsSynced(pendingRecords)
Result.success()
} else if (response.isTemporaryFailure()) {
Result.retry()
} else {
Result.failure()
}
} catch (exception: IOException) {
Result.retry()
} catch (exception: Exception) {
Result.failure()
}
}
}
Let's understand the important parts.
CoroutineWorker allows the background operation to use Kotlin coroutines. The doWork method is a suspending function, so it can call asynchronous repository operations without blocking the main thread.
The worker retrieves pending records from local storage and sends them to the backend. After a successful response, it marks the records as synchronized.
The result returned by doWork determines what happens next:
- Result.success() indicates that the task completed successfully.
- Result.retry() asks WorkManager to retry the task according to its configured backoff policy.
- Result.failure() indicates that the task has failed permanently.
The repository methods in this example represent application-specific implementations. Their responsibilities should include database access, API communication, and response handling.
One important production consideration is that a network timeout does not always mean the server failed to process the request. The server may have completed the operation even though the client did not receive the response. This is why synchronization APIs should support idempotency.
Defining Work Constraints
Not every background task should run immediately.
For example, uploading a large collection of images over a mobile network may consume significant data. An application may want to perform that operation only when an unmetered network is available.
WorkManager supports constraints that describe the conditions required before a task can run.
Common constraints include:
- Network connectivity.
- Charging state.
- Battery level.
- Device idle state.
- Storage availability.
Consider an application that should synchronize activity records whenever an internet connection is available.
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.setRequiresBatteryNotLow(true)
.build()
The CONNECTED network requirement means that the worker needs a network connection before execution.
The battery constraint prevents the task from running when the system considers the battery level too low.
For large downloads, you could use an unmetered network requirement:
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.UNMETERED)
.setRequiresCharging(true)
.build()
This configuration allows the task to run when an unmetered network is available and the device is charging.
Constraints are not permanent guarantees. If a required condition becomes unavailable while work is running, WorkManager can stop the worker and retry it when the conditions are satisfied again. Therefore, workers should be designed to handle interruption safely.
Scheduling One-Time Work
After creating the worker and its constraints, the next step is to schedule it.
fun scheduleActivitySync(context: Context) {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.setRequiresBatteryNotLow(true)
.build()
val syncRequest =
OneTimeWorkRequestBuilder<ActivitySyncWorker>()
.setConstraints(constraints)
.setBackoffCriteria(
BackoffPolicy.EXPONENTIAL,
30,
TimeUnit.SECONDS
)
.build()
WorkManager.getInstance(context)
.enqueue(syncRequest)
}
The OneTimeWorkRequestBuilder creates a request for a single execution.
The setConstraints method attaches the conditions required for execution.
The setBackoffCriteria method configures how WorkManager should wait before retrying a failed operation.
Exponential backoff increases the delay between successive retries. This helps avoid repeatedly calling an unavailable backend service.
The initial delay is a minimum, not a promise that the worker will start at that exact moment.
Preventing Duplicate Background Tasks
A common production problem occurs when the application schedules the same task multiple times.
Imagine a user opens an application several times, and each launch creates another synchronization request. Multiple workers may then attempt to upload the same records.
WorkManager provides unique work to prevent unnecessary duplicate scheduling.
Use enqueueUniqueWork when you want to maintain a single active instance of a particular one-time operation.
fun scheduleUniqueActivitySync(context: Context) {
val request =
OneTimeWorkRequestBuilder<ActivitySyncWorker>()
.build()
WorkManager.getInstance(context)
.enqueueUniqueWork(
"activity_sync",
ExistingWorkPolicy.KEEP,
request
)
}
Join the conversation! Your thoughts help the community grow.