Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 523
Jashan Chakkal Avatar asked Jul 29 '17 17:07

Jashan Chakkal


People also ask

What is broadcast receiver Kotlin?

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.

What is broadcast receiver explain in detail?

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.

How do you use a broadcast receiver?

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.


1 Answers

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) 
like image 114
v4_adi Avatar answered Sep 23 '22 09:09

v4_adi