Android Background Processing

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

Part 3: Use Android Services

18. Challenge - Services

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: 17. Use IntentService Next episode: 19. Create Foreground Services

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: 18. Challenge - Services

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

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

It’s time to practice what you’ve learned about Services! :] In this challenge, you have to do one thing - implement the Synchronization feature using a one-off service.

class SynchronizeImagesService : JobIntentService() {

  private val remoteApi by lazy { App.remoteApi }

  companion object {
    private const val JOB_ID = 15

    fun startWork(context: Context, intent: Intent) {
      enqueueWork(context, SynchronizeImagesService::class.java, JOB_ID, intent)
    }
  }
}
<service
  android:name=".service.SynchronizeImagesService"
  android:permission="android.permission.BIND_JOB_SERVICE" />
class SynchronizeImagesService : JobIntentService() {

  private val remoteApi by lazy { App.remoteApi }

  companion object {
    private const val JOB_ID = 15

    fun startWork(context: Context, intent: Intent) {
      enqueueWork(context, SynchronizeImagesService::class.java, JOB_ID, intent)
    }
  }

  override fun onHandleWork(intent: Intent) {
    clearStorage()
    fetchImages()
  }
  
  ...
}
class SynchronizeImagesService : JobIntentService() {

  ...

  private fun fetchImages() {
    GlobalScope.launch {
      val result = remoteApi.getImages()

      if (result is Success) {
        val imagesArray = result.data.map { it.imagePath }.toTypedArray()

        FileUtils.queueImagesForDownload(applicationContext, imagesArray)
      }
    }
  }

  private fun clearStorage() {
    FileUtils.clearLocalStorage(applicationContext)
  }
}
private fun synchronizeImages() {
  SynchronizeImagesService.startWork(requireContext(), Intent())
}