Get immediate access to this and over 1,500+ other videos and books.

Boost your skills with a raywenderlich.com Beginner subscription. With over 60+ video courses and our core foundational programming books bundled in one subscription, it’s simply the best investment you can make in your development career.

Implement a Simple Worker

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

Use the WorkManager API to implement a simple worker which does some work in the background.

Contributors

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

You can unlock the rest of this video course, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.

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) }

Reviews

Comments