Android Background Processing

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

Part 3: Use Android Services

20. Communicate Using BroadcastReceivers

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: 19. Create Foreground Services Next episode: 21. Challenge - Communication Between Components

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: 20. Communicate Using BroadcastReceivers

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

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

Previously you implemented a foreground service, which showed a notification. But you didn’t have a way to communicate back to the UI, that the service has finished, and that the images have been synchronized. To implement such behavior, you need to use BroadcastReceivers.

const val ACTION_IMAGES_SYNCHRONIZED = "images_synchronized"

class SynchronizeImagesReceiver(
    private inline val onImagesSynchronized: () -> Unit) : BroadcastReceiver() {

  override fun onReceive(context: Context?, intent: Intent?) {
    if (intent?.action == ACTION_IMAGES_SYNCHRONIZED) {
      onImagesSynchronized()
    }
  }
}
  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)
        stopForeground(true)
        sendBroadcast(Intent().apply {
          action = ACTION_IMAGES_SYNCHRONIZED
        })
      }
    }
  }
  private val receiver by lazy {
    SynchronizeImagesReceiver {
      toast("Images synchronized!")
    }
  }
    registerReceiver(receiver, IntentFilter().apply {
      addAction(ACTION_IMAGES_SYNCHRONIZED)
    })
unregisterReceiver(receiver)