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.

Challenge - WorkManager

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

Practice using the WorkManager API, to implement another worker and chain and observe the results.

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.

Nice job repeating the concepts from the first part of the course, and reaching your first challenge in this part! :] In this challenge, you have to implement a few things! You need to create not one, but two new workers!

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

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

    rootFolder?.listFiles()?.forEach {
      if (it.isDirectory) {
        it.deleteRecursively()
      } else {
        it.delete()
      }
    }

    return Result.success()
  }
}
class SynchronizeImagesWorker(context: Context, workerParameters: WorkerParameters) :
    Worker(context, workerParameters) {

  override fun doWork(): Result {
    val images = inputData.getStringArray("images") ?: return Result.failure()

    images.forEach { imagePath ->
      val file = File(applicationContext.externalMediaDirs.first(), imagePath)
      FileUtils.downloadImage(file, imagePath)
    }

    return Result.success()
  }
}
  fun downloadImage(file: File, imageDownloadPath: String) {
    val imageUrl = URL("$BASE_URL/files/$imageDownloadPath")

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

    val inputStream = connection.inputStream

    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 imagePath = parts.last()
val file = File(applicationContext.externalMediaDirs.first(), imagePath)

FileUtils.downloadImage(file, imagePath)
  private val remoteApi = App.remoteApi
  private val networkStatusChecker by lazy {
    NetworkStatusChecker(activity?.getSystemService(ConnectivityManager::class.java))
  }
    syncImages.setOnClickListener {
      networkStatusChecker.performIfConnectedToInternet {
        GlobalScope.launch(Dispatchers.Main) {
          val result = remoteApi.getImages()

          if (result is Success) {
            val images = result.data.map { it.imagePath }
            synchronizeImages(images)
          }
        }
      }
    }
  }
  private fun synchronizeImages(images: List<String>) {
    val clearStorageWorker = OneTimeWorkRequestBuilder<ClearLocalStorageWorker>()
        .build()

    val synchronizeImagesWorker = OneTimeWorkRequestBuilder<SynchronizeImagesWorker>()
        .setInputData(workDataOf("images" to images.toTypedArray()))
        .build()

    val workManager = WorkManager.getInstance(requireActivity())

    workManager.beginWith(clearStorageWorker)
        .then(synchronizeImagesWorker)
        .enqueue()

    workManager.getWorkInfoByIdLiveData(synchronizeImagesWorker.id).observe(this, Observer {
      if (it.state.isFinished) {
        activity?.toast("Synchronized images!")
      }
    })
  }

Reviews

Comments