Broadcast Receiver in kotlin

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.

Upvotes: 39

Views: 60334

Answers (3)

v4_adi
v4_adi

Reputation: 1533

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)

Upvotes: 101

w3bshark
w3bshark

Reputation: 2749

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

Upvotes: 11

alireza
alireza

Reputation: 524

Anonymous class syntax in Kotlin is like this:

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

    }
}

Upvotes: 11

Related Questions