Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save akueisara/1dbd40ff46fc3b8df50d5970879a1c3d to your computer and use it in GitHub Desktop.
Save akueisara/1dbd40ff46fc3b8df50d5970879a1c3d to your computer and use it in GitHub Desktop.
WorkManager Basics: Complete WorkRequest Example
// 1. Create the Constraints
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
// Other supported Constraints
val exampleConstraints = Constraints.Builder()
.setRequiresBatteryNotLow(true)
.setRequiredNetworkType(NetworkType.CONNECTED)
.setRequiresCharging(true)
.setRequiresStorageNotLow(true)
.setRequiresDeviceIdle(true)
.build()
// 2. Define the input
val imageData = workDataOf(Constants.KEY_IMAGE_URI to imageUriString)
// 3. Bring it all together by creating the WorkRequest; this also sets the back off criteria
// P.S. It is also possible to have a repeating PeriodicWorkRequest
val uploadWorkRequest = OneTimeWorkRequestBuilder<UploadWorker>()
.setInputData(imageData)
.setConstraints(constraints)
// Allows you to define when the work should be retried when a Worker return Result.retry()
.setBackoffCriteria(
// indicate that WorkManager should increase the backoff time linearly
backoffPolicy = BackoffPolicy.LINEAR, // or BackoffPolicy.EXPONENTIAL
// Time to wait before retrying the work
backoffDelay = OneTimeWorkRequest.MIN_BACKOFF_MILLIS, // 10000L
// The TimeUnit for backoffDelay
timeUnit = TimeUnit.MILLISECONDS)
.addTag("sometag")
.build()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment