Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Broadcast receiver with multiple actions

How should I implement a broadcast receiver & filter so that it can response to multiple intents.

private BroadcastReceiver myReceiver;
IntentFilter myFilter = new IntentFilter();

onCreate():

    myFilter.addAction("first");
    myFilter.addAction("second");

    myReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                // do different actions according to the intent
            }
        };

    registerReceiver(myReceiver, myFilter);

from my fragment:

Intent i = new Intent("first"); sendBroadcast(i);

Intent i = new Intent("second"); sendBroadcast(i);

Thanks

like image 453
Deidara Avatar asked Feb 07 '23 12:02

Deidara


1 Answers

@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    if(action != null) {
        if(action.equals("action1") {
            // CODE
        } else if (action.equals("action2") {
            // CODE
        }
    }
}
like image 120
W0rmH0le Avatar answered Feb 13 '23 06:02

W0rmH0le