How to use LocalBroadcastManager?

后端 未结 13 3208
天命终不由人
天命终不由人 2020-11-21 04:15

How to use/locate LocalBroadcastManager as described in google docs and Service broadcast doc?

I tried to google it, but there is no code available to s

13条回答
  •  甜味超标
    2020-11-21 05:01

    Kotlin version of using LocalBroadcastManager:

    Please check the below code for registering, sending and receiving the broadcast message.

    class MainActivity : AppCompatActivity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            // register broadcast manager
            val localBroadcastManager = LocalBroadcastManager.getInstance(this)
            localBroadcastManager.registerReceiver(receiver, IntentFilter("your_action"))
        }
    
        // broadcast receiver
        var receiver: BroadcastReceiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {
                if (intent != null) {
                    val str = intent.getStringExtra("key")
                    
                }
            }
        }
    
        /**
         * Send broadcast method
         */
        fun sendBroadcast() {
            val intent = Intent("your_action")
            intent.putExtra("key", "Your data")
            LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
        }
    
        override fun onDestroy() {
            // Unregister broadcast
            LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver)
            super.onDestroy()
        }
    
    }
    

提交回复
热议问题