Broadcast Receiver in kotlin

2019-04-04 17:58发布

问题:

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.

回答1:

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)


回答2:

Anonymous class syntax in Kotlin is like this:

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

    }
}


回答3:

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.