Android广播接收器具有多个动作

时间:2016-07-20 17:10:16

标签: java android android-intent broadcastreceiver

我应该如何实现广播接收器&过滤,以便它可以响应多个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);

来自我的片段:

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

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

由于

1 个答案:

答案 0 :(得分:5)

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