Alin
Alin

Reputation: 14571

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?

Upvotes: 0

Views: 419

Answers (2)

Ryujin
Ryujin

Reputation: 443

Looks like your activity should just bind to the service to get a Binder instance that you can use to access service methods. The service can send local broadcasts that the Activity can observe with Broadcast Receivers. My recent preference is have the service methods return LiveData instances that can be observed instead. LiveData objects are lifecycle aware so any observers will know to clean up after themselves.

Upvotes: 0

TheWanderer
TheWanderer

Reputation: 17834

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.

Upvotes: 0

Related Questions