How to use LocalBroadcastManager?

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

    I'd rather like to answer comprehensively.

    1. LocalbroadcastManager included in android 3.0 and above so you have to use support library v4 for early releases. see instructions here

    2. Create a broadcast receiver:

      private BroadcastReceiver onNotice= new BroadcastReceiver() {
      
          @Override
          public void onReceive(Context context, Intent intent) {
              // intent can contain anydata
              Log.d("sohail","onReceive called");
              tv.setText("Broadcast received !");
      
          }
      };
      
    3. Register your receiver in onResume of activity like:

      protected void onResume() {
              super.onResume();
      
              IntentFilter iff= new IntentFilter(MyIntentService.ACTION);
              LocalBroadcastManager.getInstance(this).registerReceiver(onNotice, iff);
          }
      
      //MyIntentService.ACTION is just a public static string defined in MyIntentService.
      
    4. unRegister receiver in onPause:

      protected void onPause() {
        super.onPause();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(onNotice);
      }
      
    5. Now whenever a localbroadcast is sent from applications' activity or service, onReceive of onNotice will be called :).

    Edit: You can read complete tutorial here LocalBroadcastManager: Intra application message passing

提交回复
热议问题