How to use LocalBroadcastManager?

后端 未结 13 3193
天命终不由人
天命终不由人 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:20

    On Receiving end:

    • First register LocalBroadcast Receiver
    • Then handle incoming intent data in onReceive.

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
      
            LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
            lbm.registerReceiver(receiver, new IntentFilter("filter_string"));
        }
      
        public BroadcastReceiver receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent != null) {
                    String str = intent.getStringExtra("key");
                    // get all your data from intent and do what you want 
                }
            }
        };
      

    On Sending End:

       Intent intent = new Intent("filter_string");
       intent.putExtra("key", "My Data");
       // put your all data using put extra 
    
       LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    
    0 讨论(0)
提交回复
热议问题