Need to upload files, sync data, or perform background work even after your app is closed? WorkManager is the recommended Android Jetpack library for scheduling reliable background tasks.
In this tutorial, we'll create a simple background task using WorkManager.
Add the Dependency
Add WorkManager to your app-level build.gradle.kts:
dependencies {
implementation("androidx.work:work-runtime-ktx:2.10.2")
}
Create a Worker
A Worker contains the code that runs in the background.
class SyncWorker(
context: Context,
params: WorkerParameters
) : Worker(context, params) {
override fun doWork(): Result {
Log.d("SyncWorker", "Sync started")
Thread.sleep(3000)
Log.d("SyncWorker", "Sync completed")
return Result.success()
}
}
doWork() returns:
-
Result.success()– Task completed. -
Result.failure()– Task failed. -
Result.retry()– Try again later.
Schedule the Work
Create a one-time work request and enqueue it.
val workRequest =
OneTimeWorkRequestBuilder<SyncWorker>()
.build()
WorkManager
.getInstance(this)
.enqueue(workRequest)
That's it! WorkManager will run the task in the background.
Passing Input Data
You can pass data to your Worker.
val inputData = workDataOf(
"username" to "John"
)
val workRequest =
OneTimeWorkRequestBuilder<SyncWorker>()
.setInputData(inputData)
.build()
Read the data inside the Worker:
override fun doWork(): Result {
val username = inputData.getString("username")
Log.d("Worker", "Hello $username")
return Result.success()
}
Run Periodically
For recurring tasks, use PeriodicWorkRequestBuilder.
val periodicWork =
PeriodicWorkRequestBuilder<SyncWorker>(
15,
TimeUnit.MINUTES
).build()
WorkManager
.getInstance(this)
.enqueue(periodicWork)
Note: The minimum interval for periodic work is 15 minutes.
Cancel Work
Cancel a scheduled task:
WorkManager
.getInstance(this)
.cancelWorkById(workRequest.id)
Conclusion
WorkManager is a simple and reliable way to run background tasks in Android. Whether you're syncing data, uploading files, or performing periodic work, it handles scheduling for you—even if the app is closed or the device restarts.
If you're building Android apps, WorkManager is a library worth learning.

Top comments (0)