- 1st of all we have to take BroadcastReceiver type variable which will usable later in 1st Activity.
private lateinit var receiver: BroadcastReceiver
- Either we'll take object on 1st activity or could be create new broadcast class and thereafter take object it on same activity.
receiver= object :BroadcastReceiver(){
override fun onReceive(context: Context?, intent: Intent?) {
val message=intent?.getStringExtra("message")
Log.e("roshan",message.toString())
}
}//or you can use this receiver=MessageReceiver() //but in this case you have to create separate broadcasterreceiver class
class MessageReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
var message = intent?.getStringExtra("message")
Log.e("roshan", message.toString())
Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
val activityIntent = Intent(context, MainActivity::class.java)
activityIntent.putExtra("broadcast_message", message)
activityIntent.flags=Intent.FLAG_ACTIVITY_NEW_TASK
context?.startActivity(activityIntent)
}
} - after that , we have to register broadcast on 1st activity
LocalBroadcastManager.getInstance(this).registerReceiver(receiver, IntentFilter("custom-event")) // Change action to "custom-event"
override fun onDestroy() {
super.onDestroy()
// Unregister the BroadcastReceiver
LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver)
} - After that we have to take source where we'll send broadcast. In my case I'm taking SecondActivity.
val intent = Intent("custom-event") // Change action to "custom-event"
intent.putExtra("message", "Hello from SecondActivity!")
LocalBroadcastManager.getInstance(this).sendBroadcast(intent) - Now, You'll get successfully data
0 Comments