Use of WorkManager in Android App(Part-1)

What is WorkManager

When to use WorkManager

Add WorkManager to your app

app/build.gradle

dependencies {
// Other dependencies
implementation "androidx.work:work-runtime-ktx:$versions.work"
}

build.gradle

versions.work = "2.3.4"

WorkManager Basics

How to use Work Manager in Code

Step 1 — Create a Data input object

BlurViewModel.kt

/**
* Creates the input data bundle which includes the Uri to operate on
* @return Data which contains the Image Uri as a String
*/

private fun createInputDataForUri(): Data {
val builder = Data.Builder()
imageUri?.let {
builder.putString(KEY_IMAGE_URI, imageUri.toString())
}
return builder.build()
}

Step 2 — Pass the Data object to WorkRequest

BlurViewModel.kt

internal fun applyBlur(blurLevel: Int) {
val blurRequest = OneTimeWorkRequestBuilder<BlurWorker>()
.setInputData(createInputDataForUri())
.build()
workManager.enqueue(blurRequest)
}

Step 3 — Update BlurWorker’s doWork() to get the input

BlurWorker.kt

override fun doWork(): Result {
val appContext = applicationContext

// ADD THIS LINE
val resourceUri = inputData.getString(KEY_IMAGE_URI)

// ... rest of doWork()
}

Step 4 — Blur the given URI

BlurWorker.kt

override fun doWork(): Result {
val appContext = applicationContext
val resourceUri = inputData.getString(KEY_IMAGE_URI) makeStatusNotification("Blurring image", appContext) return try {
// REMOVE THIS
// val picture = BitmapFactory.decodeResource(
// appContext.resources,
// R.drawable.test)
if (TextUtils.isEmpty(resourceUri)) {
Timber.e("Invalid input uri")
throw IllegalArgumentException("Invalid input uri")
}
val resolver = appContext.contentResolver val picture = BitmapFactory.decodeStream(
resolver.openInputStream(Uri.parse(resourceUri)))
val output = blurBitmap(picture, appContext) // Write bitmap to a temp file
val outputUri = writeBitmapToFile(appContext, output)
Result.success()
} catch (throwable: Throwable) {
Timber.e(throwable)
Result.failure()
}
}

Step 5 — Output temporary URI

BlurWorker.kt

val outputData = workDataOf(KEY_IMAGE_URI to outputUri.toString())Result.success(outputData)

Step 6 — Run your app

How to cancel Work Manager

Step 1 — Cancel the work by name

BlurViewModel.kt

internal fun cancelWork() {
workManager.cancelUniqueWork(IMAGE_MANIPULATION_WORK_NAME)
}

Work constraints

BlurViewModel.kt

// Put this inside the applyBlur() function
// Create charging constraint
val constraints = Constraints.Builder()
.setRequiresCharging(true)
.build()
// Add WorkRequest to save the image to the filesystem
val save = OneTimeWorkRequestBuilder<SaveImageToFileWorker>()
.setConstraints(constraints)
.addTag(TAG_OUTPUT)
.build()
continuation = continuation.then(save)
// Actually start the work
continuation.enqueue()
$ git clone https://github.com/googlecodelabs/android-workmanager

Senior Software Engineer | Android | Java | Kotlin|Xamarin Native Android|Flutter