Created
October 5, 2022 08:37
-
-
Save devrath/3bd8819f4373cef36c15b8aa3a3eb02c to your computer and use it in GitHub Desktop.
Demo of local broadcast
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const val CUSTOM_ACTION = "custom-action-local-broadcast" | |
class CustomLocalBroadcastReceiver : BroadcastReceiver() { | |
override fun onReceive(context: Context?, intent: Intent) { | |
val data = intent.getStringExtra("message") | |
Toast.makeText(context, data, Toast.LENGTH_LONG).show() | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.droid.code.demos.local_broadcast | |
import android.content.Intent | |
import android.content.IntentFilter | |
import android.os.Bundle | |
import androidx.appcompat.app.AppCompatActivity | |
import androidx.localbroadcastmanager.content.LocalBroadcastManager | |
import com.droid.code.databinding.ActivityLocalBroadcastBinding | |
import com.droid.code.demos.local_broadcast.reciever.CUSTOM_ACTION | |
import com.droid.code.demos.local_broadcast.reciever.CustomLocalBroadcastReciever | |
class LocalBroadcastActivity : AppCompatActivity() { | |
private lateinit var binding: ActivityLocalBroadcastBinding | |
private var receiver : CustomLocalBroadcastReciever = CustomLocalBroadcastReciever() | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
binding = ActivityLocalBroadcastBinding.inflate(layoutInflater) | |
setContentView(binding.root) | |
registerReciever() | |
binding.btnTriggerId.setOnClickListener { | |
val customIntent = Intent(CUSTOM_ACTION).putExtra("message", "CUSTOM-VALUE") | |
val localBroadcastManager = LocalBroadcastManager.getInstance(this@LocalBroadcastActivity) | |
localBroadcastManager.sendBroadcast(customIntent); | |
} | |
} | |
private fun registerReciever() { | |
val localBroadcastManager = LocalBroadcastManager.getInstance(this@LocalBroadcastActivity) | |
localBroadcastManager.registerReceiver(receiver, IntentFilter(CUSTOM_ACTION)) | |
} | |
override fun onDestroy() { | |
super.onDestroy() | |
unregisterReciever() | |
} | |
private fun unregisterReciever() { | |
val localBroadcastManager = LocalBroadcastManager.getInstance(this@LocalBroadcastActivity) | |
localBroadcastManager.unregisterReceiver(receiver) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment