Android Beginners

Lesson 26: Background Work: Introduction to WorkManager

Ahmad Najar Ahmad Najar 1 min read

Background Work: Introduction to WorkManager

Say we want to sync tasks with a server periodically, even when the app isn't open. That's a job for WorkManager, Android's official library for guaranteed, deferrable background work.

Add the dependency

implementation("androidx.work:work-runtime-ktx:2.9.1")

Define the work

class SyncTasksWorker(
    context: Context,
    params: WorkerParameters
) : CoroutineWorker(context, params) {

    override suspend fun doWork(): Result {
        return try {
            // sync logic would go here
            Result.success()
        } catch (e: Exception) {
            Result.retry()
        }
    }
}

Returning Result.retry() tells WorkManager to automatically try again later with backoff — you don't need to write your own retry logic.

Scheduling it to run periodically

val syncRequest = PeriodicWorkRequestBuilder(1, TimeUnit.HOURS)
    .setConstraints(
        Constraints.Builder()
            .setRequiredNetworkType(NetworkType.CONNECTED)
            .build()
    )
    .build()

WorkManager.getInstance(context).enqueue(syncRequest)

The Constraints here say: only run this when there's an actual network connection. You can also constrain on battery level, charging state, or storage — WorkManager waits until the constraints are satisfied before running, rather than failing immediately.

Why not just use a background thread directly?

A plain background thread dies the moment your app process is killed by the OS (which happens routinely to save memory). WorkManager persists the request — even across app restarts and device reboots — and is genuinely the correct tool any time work needs to happen reliably, not just "while the app happens to still be open."

Next: Lesson 27 — writing your first unit tests.

Android Beginners