user7021565
user7021565

Reputation: 35

Can one BroadcastReceiver be used for multiple IntentServices?

Normally for a single IntentService you can define the broadcast receiver listener like this in an Activity's onCreate() method (for example)

broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        //get stuff from the intent and do whatever you want  
    }
};

And you register the receiver like this (also in onCreate()):

LocalBroadcastManager.getInstance(this)
    .registerReceiver(broadcastReceiver, new IntentFilter("my_intent_service"));

And then you start the IntentService with:

Intent intent = new Intent(this, MyIntentService.class);
startService(intent);

And in the IntentService you send messages back to the receiver with:

Intent broadcastIntent = new Intent("my_intent_service");
broadcastIntent.putExtra("whateverData", whateverData);
LocalBroadcastManager.getInstance(this).sendBroadcast(broadcastIntent);

which triggers the onReceive method described earlier.

And then to unregister the receivers, in onDestroy method you can do:

  LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver);

In the Manifest file, you add for your service:

<service
    android:name=".MyIntentService"
    android:exported="false" />

I want to receive broadcasts from multiple IntentServices in the same Activity.

Do you need one receiver per IntentService? As in, if I make n IntentServices do I need to register n receivers, make n listener, and unregister n receivers in onDestroy?

Upvotes: 3

Views: 5781

Answers (2)

HelloSadness
HelloSadness

Reputation: 955

yes you can use one broadcast receiver in one activity, that would handle multiple intents from different services. I’d recommend to add multiple intent-filter to your broadcast receiver to make distinction from which Service you are getting a broadcast.

Upvotes: 4

OlivierM
OlivierM

Reputation: 3212

The way to filter multiple actions with one BroadcastReceiver is to add them to the IntentFilter:

IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("my_intent_service1"); // Action1 to filter
intentFilter.addAction("my_intent_service2"); // Action2 to filter
LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, intentFilter);

And in your BroadcastReceiver:

private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals("my_intent_service1")) {
            // Action 1
        } else if (intent.getAction().equals("my_intent_service2")) {
            // Action 2
        }
    }
};

Upvotes: 6

Related Questions