Android – Architecture – How to listen a source and update destination screen in real time by BroadcastManager?

Destination Activity/ Fragment

Register BroadcastReceiver

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
 LocalBroadcastManager.getInstance(requireContext()).registerReceiver(
            dataChangeReceiver(), IntentFilter("UNIQUE_LISTENER_KEY")
        )
    }

    private fun dataChangeReceiver(): BroadcastReceiver {
        return object: BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {
                // Do stuffs here
                ...
            }
        }
    }

Source Activity/ Fragment

Send Broadcast signal

    private fun doSomeStuffs() {
        ...

        val dataChange = Intent("UNIQUE_LISTENER_KEY")
LocalBroadcastManager.getInstance(requireContext()).sendBroadcast(dataChange)
    }

Be the first to comment

Leave a Reply

Your email address will not be published.


*