Broadcast Receiver in kotlin

后端 未结 3 1747
时光取名叫无心
时光取名叫无心 2020-12-29 04:40

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 a

相关标签:
3条回答
  • 2020-12-29 04:48

    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)
    
    0 讨论(0)
  • 2020-12-29 04:50

    Anonymous class syntax in Kotlin is like this:

    val receiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
    
        }
    }
    
    0 讨论(0)
  • 2020-12-29 05:00

    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.

    0 讨论(0)
提交回复
热议问题