Broadcast Receiver in kotlin

Robin CK picture Robin CK · Jul 29, 2017 · Viewed 32.5k times · Source

How to use register and create a Broadcast Receiver in Android in Kotlin. Any advice... In Java, you can create it by declaring it as a Broadcast Receiver. But in Kotlin I am not able to find Broadcast Receiver ...well if it is there then how to use it.

Answer

v4_adi picture v4_adi · Jul 30, 2017

you can do it in the following way

Create a broadcast receiver object in your activity class

 val broadCastReceiver = object : BroadcastReceiver() {
        override fun onReceive(contxt: Context?, intent: Intent?) {

            when (intent?.action) {
                BROADCAST_DEFAULT_ALBUM_CHANGED -> handleAlbumChanged()

                BROADCAST_CHANGE_TYPE_CHANGED -> handleChangeTypeChanged()
            }
           }
          }

Register broadcast receiver in onCreate() function of your activity

 LocalBroadcastManager.getInstance(this)
                    .registerReceiver(broadCastReceiver, IntentFilter(BROADCAST_DEFAULT_ALBUM_CHANGED))

unregister it in ondestroy function of your activity

LocalBroadcastManager.getInstance(this)
                .unregisterReceiver(broadCastReceiver)