是否可以使用简单的代码一次性注册它们? 或者他们必须逐一取消注册?
答案 0 :(得分:7)
我知道这是一个老问题,但为什么不使用广播接收器来获取一个意图,然后触发所有接收器取消注册? (想要发布比当前答案更准确的内容)
在响应的片段/活动中,你把它放在:
public class PanicFragment extends Fragment {
IntentFilter killFilter = new IntentFilter("your.app.name.some.awesome.action.title");
BroadcastReceiver kill = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
context.unregisterReceiver(receiver); // The actual receiver you want to unreigster
context.unregisterReceiver(this); // The one you just created
}
};
(不要忘记在创建片段/活动时最初注册接收器)
在您的服务或其他活动中,或者您想要的任何内容:
private void callThisToUnregisterAllYourReceivers(Context context) {
Intent killThemAll = new Intent();
killThemAll.setAction("your.app.name.some.awesome.action.title");
context.sendBroadcast(killThemAll);
}
我希望这在任何方面都有帮助
答案 1 :(得分:6)
你必须逐一做到这一点。活动不应该有很多,如果有的话,所以我不希望这太繁琐。
答案 2 :(得分:0)
我不会使用其他BroadcastReceiver
删除其他广播接收器。
以下是我在应用程序类中添加的内容:
private static List<BroadcastReceiver> broadcastReceivers = new LinkedList<>();
public void addReceiver(BroadcastReceiver receiver, IntentFilter filter) {
mContext.registerReceiver(receiver, filter);
broadcastReceivers.add(receiver);
}
public void removeReceiver(BroadcastReceiver receiver) {
unregisterReceiver(receiver);
broadcastReceivers.remove(receiver);
}
public List<BroadcastReceiver> getAllReceivers() {
return broadcastReceivers;
}
public void removeAllReceivers() {
for (BroadcastReceiver receiver : getAllReceivers()) {
removeReceiver(receiver);
}
}