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.

Communicate Using BroadcastReceivers

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

Implement the go-to way for communication between Android components which are used for background processing - BroadcastReceivers.

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.

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)

Reviews

Comments