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 - DownloadManager

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

Practice using the DownloadManager, to add more support for download progress.

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.

To finish off the WorkManager and DownloadManager practice, you first have to solve a challenge! In this challenge, you have to replace the SynchronizeImageWorker code, with the DownloadManager. Here’s a hint, you can extract the code for the DownloadManager, to the FileUtils, and then reuse it for each image you have to download!

  fun queueImagesForDownload(context: Context, images: Array<String>) {
    if (images.isNotEmpty()) {
      val downloadManager = context.getSystemService(DownloadManager::class.java)

      val requests = images.mapNotNull { imageUrl ->
        val file = File(context.externalMediaDirs.first(), imageUrl)

        buildDownloadManagerRequest(file, imageUrl)
      }

      requests.forEach { request -> downloadManager?.enqueue(request) }
    }
  }
  
private fun buildDownloadManagerRequest(file: File, imageUrl: String): DownloadManager.Request? {
    return DownloadManager.Request(Uri.parse("$BASE_URL/files/$imageUrl"))
        .setTitle("Image download")
        .setDescription("Downloading")
        .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE)
        .setDestinationUri(Uri.fromFile(file))
        .setAllowedOverMetered(true)
        .setAllowedOverRoaming(false)
  }
FileUtils.queueImagesForDownload(applicationContext, images)
FileUtils.queueImagesForDownload(requireContext(), arrayOf(imageUrl))

Reviews

Comments