我试图用a BroadcastReceiver
来处理多个动作.接收器注册了一个intent过滤器,但这限制了我只向接收器发送一种动作类型的意图(参见参考资料Intent.getAction();
)
这是我的BroadcastReceiver
类以及我想要处理其中的操作的方式.
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 } } }
我注册意图的地方看起来像这样(在服务类中):
@Override public void onCreate() { super.onCreate(); mbr = new MyBroadcastReceiver(); this.registerReceiver(mbr, new IntentFilter("MyBroadcastReceiver")); }
我打电话的方式看起来像这样(实际上我只是设置了一个按钮的监听器):
//creating the pending intent PendingIntent myPendingIntent = PendingIntent.getBroadcast(this, 0, new Intent("MyBroadcastReceiver"), 0); //add button listener remoteViews.setOnClickPendingIntent(R.id.my_button, myPendingIntent);
这种方式迫使我为每个想要传递给MyBroadcastReceiver的意图设置setAction("MyBroadcastReceiver").
但是我想传递具有不同动作的意图,我该怎么办?
或者这不是一个好的方法,最好是为每个不同的意图BroadcastReceiver
使用它自己的单独实现IntentFilter
?
BroadcastReceiver
可以处理多个操作,将它们添加到intent过滤器
IntentFilter filter = new IntentFilter(); filter.addAction("action1"); filter.addAction("action2");
然后用该过滤器注册它
registerReceiver(mbr, filter);
并在你自己的接收器内切换动作
switch(intent.getAction()){ case action1: // do something break; case action2: // do something break; }