Deferrable Background Work (WorkManager)
WorkManager for Guaranteed Work
For work that must run even if the app closes (syncing, uploads), use `WorkManager`. It survives process death and reboots, respects constraints (network, charging), and retries with backoff.
📚 Explanation
`WorkManager` is the standard API for deferrable, guaranteed background work. Extending `CoroutineWorker` lets `doWork()` be a `suspend` function. `Constraints` gate execution (e.g. only on Wi-Fi/charging); `Result.retry()` plus a backoff policy handles transient failures. `enqueueUniquePeriodicWork` with `KEEP` prevents scheduling duplicate jobs across app launches.
Note: Code execution is not available for Android/Kotlin in the browser. Use Android Studio to run and test the app.
import android.content.Contextimport androidx.work.*import java.util.concurrent.TimeUnit// 1. Define the unit of workclass SyncWorker(context: Context,params: WorkerParameters) : CoroutineWorker(context, params) {override suspend fun doWork(): Result {return try {// suspend work runs on a background dispatcheruploadPendingData()Result.success()} catch (e: Exception) {// Ask WorkManager to retry later with backoffResult.retry()}}}// 2. Schedule it with constraintsfun scheduleSync(context: Context) {val constraints = Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()val request = PeriodicWorkRequestBuilder<SyncWorker>(6, TimeUnit.HOURS).setConstraints(constraints).setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS).build()WorkManager.getInstance(context).enqueueUniquePeriodicWork("data-sync",ExistingPeriodicWorkPolicy.KEEP, // don't duplicate an existing jobrequest)}