androidbroadcastreceiverandroid-servicelocalbroadcastmanager

Drawbacks in registering receivers in both the activity and service?


The scenario is like this: I have an activity and a service. There are a few things that need to be sent between both:

Since this looks more as a two-way communication, I am thinking of using LocalBroadcastManager and have something like:

public class MyActivity extents Activity{

   private void receiver = new BroadcastReceiver(){
      onReceive(){
        //Handle Message from Service
      }
  }

  onResume -> LocalBroadcastManager.registerReceiver(receiver);
  onPause  -> LocalBroadcastManager.unregisterReceiver(); 
} 

and for service

public class MyService extents Service{

   private void receiver = new BroadcastReceiver(){
      onReceive(){
        //Handle Message from Activity
      }
  }

  onStart-> LocalBroadcastManager.registerReceiver(receiver);
  onDestroy-> LocalBroadcastManager.unregisterReceiver(); 
} 

This would allow to avoid binding or other methods of communication between app components but in the same time allows both to sent intents and listen for observers. Are there any drawbacks on this method?


Solution

  • There shouldn't be.

    This is the recommended way of cross-component communication within an Android app. You're doing exactly what Google recommends, with local broadcasts instead of global broadcasts.

    In a comment, you mentioned that binding a Service is usually what to do for Activity->Service communication. You don't need to use this in most cases. Binding a Service is kind of annoying, since it isn't instant and you need to use a listener to store a reference to the Binder. Broadcasts, in comparison, are relatively simple.