Interview frequency: …
Short answer
It is a library for managing tasks guaranteed to execute even if the app is closed or the device is restarted, with the ability to tie them to constraints such as internet connectivity or charging.
Explanation
WorkManager internally relies on JobScheduler on modern versions and stores the tasks in a local SQLite database to guarantee their persistence. It lets you specify conditions for running the task, and if the conditions are lost during work, the worker is stopped safely and rescheduled automatically using exponential backoff policies.
Code example
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.UNMETERED) // Requires a network connection Wi-Fi
.setRequiresCharging(true) // Requires a charger connection
.build()
val uploadWork = OneTimeWorkRequestBuilder<UploadWorker>()
.setConstraints(constraints)
.setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 15, TimeUnit.MINUTES)
.build()
WorkManager.getInstance(context).enqueue(uploadWork)Common mistakes
- Using WorkManager for quick immediate tasks that must complete only at the current moment during user interaction, where a regular CoroutineScope is much better.