Android Background Processing

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

Part 2: Use WorkManager in Complex Apps

09. Implement WorkManager in Complex Apps

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: 08. Set Up the Project Next episode: 10. Chain Work

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: 09. Implement WorkManager in Complex Apps

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

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Now that you’ve set up the projects and everything you need to work through this course, you can implement the work manager! :] Let’s move to the project!

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

  override fun doWork(): Result {

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

  override fun doWork(): Result {
    val imageDownloadPath = inputData.getString("image_path") ?: return Result.failure()
    val imageUrl = URL(imageDownloadPath)

    val connection = imageUrl.openConnection() as HttpURLConnection
    connection.doInput = true
    connection.connect()

    val imagePath = "${System.currentTimeMillis()}.jpg"
    val inputStream = connection.inputStream
    val file = File(applicationContext.externalMediaDirs.first(), imagePath)
  }
}
class DownloadImageWorker(context: Context, workerParameters: WorkerParameters) :
    Worker(context, workerParameters) {

  override fun doWork(): Result {
    val imageDownloadPath = inputData.getString("image_path") ?: return Result.failure()
    val imageUrl = URL(imageDownloadPath)

    val connection = imageUrl.openConnection() as HttpURLConnection
    connection.doInput = true
    connection.connect()

    val imagePath = "${System.currentTimeMillis()}.jpg"
    val inputStream = connection.inputStream
    val file = File(applicationContext.externalMediaDirs.first(), imagePath)

    val outputStream = FileOutputStream(file)
    outputStream.use { output ->
      val buffer = ByteArray(4 * 1024)

      var byteCount = inputStream.read(buffer)
      while (byteCount > 0) {
        output.write(buffer, 0, byteCount)

        byteCount = inputStream.read(buffer)
      }

      output.flush()
    }

    val output = workDataOf("image_path" to file.absolutePath)
    return Result.success(output)
  }
}
    val constraints = Constraints.Builder()
        .setRequiredNetworkType(NetworkType.NOT_ROAMING)
        .setRequiresBatteryNotLow(true)
        .setRequiresStorageNotLow(true)
        .build()

    val downloadImageWorker = OneTimeWorkRequestBuilder<DownloadImageWorker>()
        .setInputData(workDataOf("image_path" to imageUrl))
        .setConstraints(constraints)
        .build()
    val constraints = Constraints.Builder()
        .setRequiredNetworkType(NetworkType.NOT_ROAMING)
        .setRequiresBatteryNotLow(true)
        .setRequiresStorageNotLow(true)
        .build()

    val downloadImageWorker = OneTimeWorkRequestBuilder<DownloadImageWorker>()
        .setInputData(workDataOf("image_path" to imageUrl))
        .setConstraints(constraints)
        .build()

    val workManager = WorkManager.getInstance(requireActivity())
    workManager.enqueue(downloadImageWorker)

    workManager.getWorkInfoByIdLiveData(downloadImageWorker.id)
        .observe(this, Observer { workInfo ->
          if (workInfo?.state?.isFinished == true) {
            activity?.toast("Image downloaded!")
          }
        })