Android Background Processing

Sep 23 2022 · Kotlin 1.6, Android 12, Android Studio Chipmunk 2021.2.1

Part 1: Run Background Work

05. Challenge - Workers

Episode complete

Play next episode

Next
About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 04. Expect a Result From Workers Next episode: 06. Conclusion

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Notes: 05. Challenge - Workers

The student materials have been reviewed and are updated as of SEPTEMBER 2022.

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

To master using the WorkManager API, before implementing it in a more complex application, you first have to solve a fun challenge! :] In this challenge you have to build a worker to apply a sepia filter to your bitmap. Here’s a hint: the Sepia Filter code is prepared for you, in the ImageUtils class!

class SepiaFilterWorker(context: Context, workerParameters: WorkerParameters) :
    Worker(context, workerParameters) {

  override fun doWork(): Result {

  }
}
class SepiaFilterWorker(context: Context, workerParameters: WorkerParameters) :
    Worker(context, workerParameters) {

  override fun doWork(): Result {
    val imagePath = inputData.getString("image_path") ?: return Result.failure()
    val bitmap = BitmapFactory.decodeFile(imagePath)
    val newBitmap = ImageUtils.applySepiaFilter(bitmap)

    val outputStream = FileOutputStream(imagePath)
    outputStream.use { output ->
      newBitmap.compress(Bitmap.CompressFormat.PNG, 100, output)

      output.flush()
    }

    val output = workDataOf("image_path" to imagePath)
    return Result.success(output)
  }
}
val sepiaFilterWorker = OneTimeWorkRequestBuilder<SepiaFilterWorker>()
    .setConstraints(constraints)
    .build()

workManager.beginWith(clearFilesRequest)
  .then(downloadRequest)
  .then(sepiaFilterWorker)
  .enqueue()
workManager.getWorkInfoByIdLiveData(sepiaFilterWorker.id)