Member-only story
What should you know about Android WorkManager Constraints?
Not a member ? No worries click here!
Introduction
WorkManager is preferred option for handling deferrable background jobs on Android. For example, any background job that must execute even across system reboots or application process death.
One of the main features of the WorkManager API is its ability to execute only when certain system “Constraints” are met.
Let’s take an example of a Media download Worker, which syncs(downloads) media from remote server to the app at least once every day. Most of you would have guessed right!, we need to use WorkManager Worker that executes periodically.
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.UNMETERED) // Wi-Fi only
.setRequiresCharging(true) // Charging required
.build()
val periodicWorkRequest = PeriodicWorkRequestBuilder<DownloadWorker>(6, TimeUnit.HOURS)
.setConstraints(constraints)
.setInputData(inputData)
.build()
WorkManager.getInstance(context).enqueueUniquePeriodicWork(
"download_work",
ExistingPeriodicWorkPolicy.UPDATE, // Ensures only one instance runs
periodicWorkRequest
)
Breaking the above code snippet, we have provided constraints that gives the WorkManager idea about the ideal system conditions to execute the work .