android – Broadcast Receiver in kotlin-ThrowExceptions

Exception or error:

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 there is no Broadcast Receiver function…well if it is there then I am not able to find it or how to use it.

How to solve:

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)

###

Anonymous class syntax in Kotlin is like this:

val receiver = object : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {

    }
}

###

I’ve created a BroadcastReceiver Kotlin extension, which you can copy/paste anywhere.
It doesn’t do much more than what is already mentioned, but it reduces some of the boilerplate. 😀

Using this extension, you should register/unregister like so:

private lateinit var myReceiver: BroadcastReceiver

override fun onStart() {
    super.onStart()
    myReceiver = registerReceiver(IntentFilter(BROADCAST_SOMETHING_HAPPENED)) { intent ->
        when (intent?.action) {
            BROADCAST_SOMETHING_HAPPENED -> handleSomethingHappened()
        }
    }
}

override fun onStop() {
    super.onStop()
    unregisterReceiver(myReceiver)
}

Leave a Reply

Your email address will not be published. Required fields are marked *