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.
Broadcast in android is the system-wide events that can occur when the device starts, when a message is received on the device or when incoming calls are received, or when a device goes to airplane mode, etc. Broadcast Receivers are used to respond to these system-wide events.
A broadcast receiver (receiver) is an Android component which allows you to register for system or application events. All registered receivers for an event are notified by the Android runtime once this event happens.
An application listens for specific broadcast intents by registering a broadcast receiver in AndroidManifest. xml file. Consider we are going to register MyReceiver for system generated event ACTION_BOOT_COMPLETED which is fired by the system once the Android system has completed the boot process.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With