Flowryn
Flowryn

Reputation: 1447

How to use BroadcastReceiver to handle multiple actions?

I am trying to use a BroadcastReceiver to handle multiple actions. The receiver is registered with an intent filter, but this restricts me of sending only one action type of intents to the receiver(seeIntent.getAction();)

This is my BroadcastReceiver class and the way how I want to handle actions inside it.

class MyBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
        switch(...){  //the criteria for switching to a particular case
                    ... //some cases to handle here
        }           
    }
}

The place where I register the intent looks like this(in the service class):

@Override
public void onCreate() {
    super.onCreate();
    mbr = new MyBroadcastReceiver();
    this.registerReceiver(mbr, new IntentFilter("MyBroadcastReceiver"));
}

The way how I make a call looks like this(actually I just set a listener to a button):

   //creating the pending intent
   PendingIntent myPendingIntent = PendingIntent.getBroadcast(this, 0, new Intent("MyBroadcastReceiver"), 0);
   //add button listener
   remoteViews.setOnClickPendingIntent(R.id.my_button, myPendingIntent);

This way forces me to setAction("MyBroadcastReceiver") for each intent I want to pass to MyBroadcastReceiver.

However I want to pass intents that have different actions, how should I proceed?

Or this is not a good approach and is better to use for each different intent a separate BroadcastReceiver implementation with it's own IntentFilter?

Upvotes: 1

Views: 5271

Answers (2)

Rajen Raiyarela
Rajen Raiyarela

Reputation: 5636

You can register one or more action for broadcast receiver using IntentFilter as below:-

IntentFilter filter = new IntentFilter();
filter.addAction("Action1");
filter.addAction("Action2");
filter.addAction("Action3");

this.registerReceiver(mbr, filter);

Upvotes: 1

SaNtoRiaN
SaNtoRiaN

Reputation: 2202

BroadcastReceiver can handle multiple actions, add them to the intent filter

IntentFilter filter = new IntentFilter();
filter.addAction("action1");
filter.addAction("action2");

then register it with that filter

registerReceiver(mbr, filter);

and inside your own receiver switch for actions

switch(intent.getAction()){
    case action1:
        // do something
        break;
    case action2:
        // do something
        break;
}

Upvotes: 8

Related Questions