Java – Android broadcast receiver with multiple operations

Android broadcast receiver with multiple operations… here is a solution to the problem.

Android broadcast receiver with multiple operations

How should I implement the broadcast sink and filter so that it can respond 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);

Fragment from self:

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

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

Thanks

Solution

@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
        }
    }
}

Related Problems and Solutions