0

So I have two Services in my app FooService and BarService. What would be the most efficient way to communicate between these services? More specifically, how is communication via sending intents with actions using startForegrounService different from sending broadcasts using local broadcast manager?

Using onStartCommand

FooService.class

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    final int i = super.onStartCommand(intent, flags, startId);
    String intentAction = null;
    if(intent!=null)
        intentAction = intent.getAction();
    if(intentAction ==null)
        return i;
    switch (intentAction) {
        case "Message A":
         // do something with Message A    

            break;
        case "Message B":
         // do something with Message B
        default:
            return i;
    }
    return i;
}

BarService.class

Intent myIntent = new Intent(this, FooService.class).setAction("Message A");

startService(myIntent);

1 Answers1

0

Best would be to use a LocalBroadCast Manager. Using Intents to start and stop service you will have to handle onStartCommand everytime rather start both the services and use LocalBroadCast Manager to communicate is much efficient.

In your Foo Service,

LocalBroadcastManager broadcaster;
 @Override
    public void onCreate() {
        broadcaster = LocalBroadcastManager.getInstance(this);
    }

Send your broadcast

Intent intent = new Intent("com.FooService");
 broadcaster.sendBroadcast(intent);

In your BarService,

private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            //Your Action here

        }
    };


@Override
    protected void onCreate() {
        super.onCreate();
        LocalBroadcastManager.getInstance(this).registerReceiver((mMessageReceiver),
                new IntentFilter("com.FooService")
        );
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
    }

EDIT 1

Comparing a Bound service and a LocalBroadCast manager bound services are much more efficient because they only bind once and can communicate with each other without needing to start any Intents.

Here is an example explaining the binding

oldcode
  • 1,669
  • 3
  • 22
  • 41
  • Thanks, I understand that we need to handle intents at onStartCommand(). However, I think this is trivial, and more straight-forward than a LocalBroadcastReceiver. Do you know if one is more efficient than the other? If so, why? –  Mar 08 '18 at 16:59