Broadcast Receiver in kotlin

北慕城南 提交于 2019-12-03 15:22:14

问题


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. 😀

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)
}


来源:https://stackoverflow.com/questions/45392037/broadcast-receiver-in-kotlin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!