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.

Use the JobScheduler

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

Implement the JobService, powered by the JobScheduler API, to run tasks with constraints, similar to WorkManager’s Workers.

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.

The next legacy mechanism you’ll use for background processing is the JobScheduler. It’s actually very similar to how the WorkManager is implemented. But it has some key differences when it comes to communicating the Result output data.

class DownloadImageJobService : JobService() {

  override fun onStartJob(params: JobParameters?): Boolean {
    val imagePath = params?.extras?.getString("image_path")
  }
}
    <service
      android:name=".DownloadImageJobService"
      android:permission="android.permission.BIND_JOB_SERVICE" />
class DownloadImageJobService : JobService() {

  override fun onStartJob(params: JobParameters?): Boolean {
    val imagePath = params?.extras?.getString("image_path")

    return if (imagePath != null) {
      downloadImage(imagePath)
      true
    } else {
      jobFinished(null, false)
      false
    }
  }

  private fun downloadImage(imageDownloadPath: String) {
    Thread(Runnable {
    }).start()
  }
}
class DownloadImageJobService : JobService() {

  override fun onStartJob(params: JobParameters?): Boolean {
    val imagePath = params?.extras?.getString("image_path")

    return if (imagePath != null) {
      downloadImage(imagePath)
      true
    } else {
      jobFinished(null, false)
      false
    }
  }

  private fun downloadImage(imageDownloadPath: String) {
    Thread(Runnable {
        val imageUrl = URL(imageDownloadPath)
        val connection = imageUrl.openConnection() as HttpURLConnection
        connection.doInput = true
        connection.connect()

        val imagePath = "owl_image_${System.currentTimeMillis()}.jpg"
        val inputStream = connection.inputStream
        val file = File(applicationContext.externalMediaDirs.first(), imagePath)
    }).start()
  }
}
class DownloadImageJobService : JobService() {

...

  private fun downloadImage(imageDownloadPath: String) {
    Thread(Runnable {
      try {
        val imageUrl = URL(imageDownloadPath)
        val connection = imageUrl.openConnection() as HttpURLConnection
        connection.doInput = true
        connection.connect()

        val imagePath = "owl_image_${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()
        }
    }).start()
  }
}
class DownloadImageJobService : JobService() {

...

  private fun downloadImage(imageDownloadPath: String) {
    Thread(Runnable {
      try {
        ...
        
        sendBroadcast(Intent().apply {
          action = ACTION_IMAGE_DOWNLOADED
          putExtra("image_path", file.absolutePath)
        })
      } catch (error: Throwable) {
        jobFinished(null, false)
      }
    }).start()
  }
}
        sendBroadcast(Intent().apply {
          action = ACTION_IMAGE_DOWNLOADED
          putExtra("image_path", file.absolutePath)
        })
class DownloadImageJobService : JobService() {

...

  override fun onStopJob(params: JobParameters?): Boolean {
    return false
  }
}
const val ACTION_IMAGE_DOWNLOADED = "image_downloaded"

class ImageDownloadedReceiver(
    private val onImageDownloaded: (String) -> Unit
) : BroadcastReceiver() {}
const val ACTION_IMAGE_DOWNLOADED = "image_downloaded"

class ImageDownloadedReceiver(
    private val onImageDownloaded: (String) -> Unit
) : BroadcastReceiver() {

  override fun onReceive(context: Context?, intent: Intent?) {

  }
}
const val ACTION_IMAGE_DOWNLOADED = "image_downloaded"

class ImageDownloadedReceiver(
    private val onImageDownloaded: (String) -> Unit
) : BroadcastReceiver() {

  override fun onReceive(context: Context?, intent: Intent?) {
    if (intent?.action != ACTION_IMAGE_DOWNLOADED) {
      return
    }

    val imagePath = intent.getStringExtra("image_path")

    if (imagePath != null) {
      onImageDownloaded(imagePath)
    }
  }
}
  private val receiver by lazy {
    ImageDownloadedReceiver {
      displayImage(it)
    }
  }

    registerReceiver(receiver, IntentFilter().apply {
      addAction(ACTION_IMAGE_DOWNLOADED)
    })
    
  override fun onDestroy() {
    unregisterReceiver(receiver)
    super.onDestroy()
  }
val jobScheduler = getSystemService(JobScheduler::class.java) ?: return
const val LOAD_IMAGE_JOB_ID = 10

    val jobScheduler = getSystemService(JobScheduler::class.java) ?: return

    jobScheduler.schedule(JobInfo.Builder(LOAD_IMAGE_JOB_ID,
        ComponentName(this, DownloadImageJobService::class.java))
        .build())
    val jobScheduler = getSystemService(JobScheduler::class.java) ?: return

    jobScheduler.schedule(JobInfo.Builder(LOAD_IMAGE_JOB_ID,
        ComponentName(this, DownloadImageJobService::class.java))
        .setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
        .setExtras(PersistableBundle().apply {
          putString("image_path", "https://wallpaperplay.com/walls/full/1/c/7/38027.jpg")
        })
        .setOverrideDeadline(1500)
        .build())

Reviews

Comments