Android 广播的接收器与多个操作

发布时间: 2016/9/26 4:16:07
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

应该如何实施广播的接收器 & filter ,它可以响应多 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 :

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

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

谢谢你

解决方法 1:

@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
        }
    }
}
官方微信
官方QQ群
31647020