Android Background Processing

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

Part 1: Run Background Work

03. Implement a Simple Worker

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: 02. Launch Threads & Post to the Main Thread Next episode: 04. Expect a Result From 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: 03. Implement a Simple Worker

The student materials have been reviewed and are updated as of SEPTEMBER 2022. Image url has changed.

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

After the brief revision of threading, you’re ready to start learning about more concepts in Android backround processing. The first concept you’ll cover is the WorkManager API.

implementation "androidx.work:work-runtime-ktx:2.3.4"
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }

  kotlinOptions {
    jvmTarget = JavaVersion.VERSION_1_8
  }
class DownloadWorker(context: Context, workerParameters: WorkerParameters) :
    Worker(context, workerParameters) {

  override fun doWork(): Result {
    
  }
}
class DownloadWorker(context: Context, workerParameters: WorkerParameters) :
    Worker(context, workerParameters) {

  override fun doWork(): Result {
    val imageUrl = URL("https://cdn.pixabay.com/photo/2018/01/14/23/12/nature-3082832__480.jpg")
    val connection = imageUrl.openConnection() as HttpURLConnection
    connection.doInput = true
    connection.connect()

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

  override fun doWork(): Result {
    val imageUrl = URL("https://cdn.pixabay.com/photo/2018/01/14/23/12/nature-3082832__480.jpg")
    val connection = imageUrl.openConnection() as HttpURLConnection
    connection.doInput = true
    connection.connect()

    val imagePath = "owl_image.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()
    }

    return Result.success()
  }
}
private fun downloadImage() {
  val constraints = Constraints.Builder()
      .setRequiresBatteryNotLow(true)
      .setRequiresStorageNotLow(true)
      .setRequiredNetworkType(NetworkType.NOT_ROAMING)
      .build()
}
private fun downloadImage() {
  val constraints = Constraints.Builder()
      .setRequiresBatteryNotLow(true)
      .setRequiresStorageNotLow(true)
      .setRequiredNetworkType(NetworkType.NOT_ROAMING)
      .build()

  val downloadRequest = OneTimeWorkRequestBuilder<DownloadWorker>()
      .setConstraints(constraints)
      .build()
}
private fun downloadImage() {
  val constraints = Constraints.Builder()
      .setRequiresBatteryNotLow(true)
      .setRequiresStorageNotLow(true)
      .setRequiredNetworkType(NetworkType.NOT_ROAMING)
      .build()

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

  val workManager = WorkManager.getInstance(this)

  workManager.enqueue(downloadRequest)
}
private fun downloadImage() {
  val constraints = Constraints.Builder()
      .setRequiresBatteryNotLow(true)
      .setRequiresStorageNotLow(true)
      .setRequiredNetworkType(NetworkType.NOT_ROAMING)
      .build()

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

  val workManager = WorkManager.getInstance(this)

  workManager.enqueue(downloadRequest)

  workManager.getWorkInfoByIdLiveData(downloadRequest.id).observe(this, Observer { info ->
    if (info.state.isFinished) {
      val imageFile = File(externalMediaDirs.first(), "owl_image.jpg")
      displayImage(imageFile.absolutePath)
    }
  })
}
private fun displayImage(imagePath: String) {
  GlobalScope.launch(Dispatchers.Main) {
    val bitmap = loadImageFromFile(imagePath)

    image.setImageBitmap(bitmap)
  }
}

private suspend fun loadImageFromFile(imagePath: String): Bitmap =
    withContext(Dispatchers.IO) { BitmapFactory.decodeFile(imagePath) }