Android Background Processing

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

Part 1: Run Background Work

04. Expect a Result From 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: 03. Implement a Simple Worker Next episode: 05. Challenge - Workers

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: 04. Expect a Result From 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.

Now that you know how to implement a Worker, it’s time to implement another one, add results to your workers, and chain them together! Let’s see how to do so! :]

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

  override fun doWork(): Result {
    val root = applicationContext.externalMediaDirs.first()

    return try {
      root.listFiles()?.forEach { child ->
        if (child.isDirectory) {
          child.deleteRecursively()
        } else {
          child.delete()
        }
      }

      Result.success()
    } catch (error: Throwable) {
      error.printStackTrace()
      Result.failure()
    }
  }
}
val imagePath = "owl_image_${System.currentTimeMillis()}.jpg"
val inputStream = connection.inputStream
val file = File(applicationContext.externalMediaDirs.first(), imagePath)

...

val output = workDataOf("image_path" to file.absolutePath)
return Result.success(output)
val clearFilesRequest = OneTimeWorkRequestBuilder<FileClearWorker>()
    .build()
val clearFilesRequest = OneTimeWorkRequestBuilder<FileClearWorker>()
    .build()

val downloadRequest = OneTimeWorkRequestBuilder<DownloadWorker>()
    .setConstraints(constraints)
    .build()

val workManager = WorkManager.getInstance(this)

workManager.beginWith(clearFilesRequest)
.then(downloadRequest)
.enqueue()
val imagePath = info.outputData.getString("image_path")

if (!imagePath.isNullOrEmpty()) {
  displayImage(imagePath)
}