0

我有一个 BroadcastReceiver(#1) 一直在运行以捕获事件。当事件发生时,它可能需要对特定活动进行 UI 更改(如果该活动处于活动状态)。为此,我让 BroadcastReceiver#1 创建了一个新意图,该意图被活动上的第二个 BroadcastReceiver(#2) 捕获,并且仅在 Activity 未暂停时才注册/取消注册……如此处所述: 仅当它在前台时才从 BroadcastReceiver 通知 Activity

所有这些都在工作......但是,现在我希望 BroadcastReceiver#1 在活动未处于焦点或处于焦点但选择不处理事件时发布状态通知。因此,Activity(如果处于活动状态)需要某种方式与 BroadcastReceiver#1 进行通信。

我以为我会让 BroadcastReceiver#1 生成一个线程,该线程将在 X 秒后发布带有通知的事件......该线程将有第三个 broadcastreceiver#3,如果接收活动选择处理事件,它可以发送“不要打扰发布该通知”意图,该意图将被 BroadcastReceiver#3 捕获以中止通知。但是,这不起作用,因为Android 不允许一个BroadcastReceiver 注册另一个BroadcastReceiver。

4

1 回答 1

0

Have never used it, but should work. Just before sending broadcast query whether any broadcast recievers are ready to handle your intent .

PackageManager pm = context.getPackageManager();
List<ResolveInfo>  mList = pm.queryBroadcastReceivers(intent, 0);

if(mList.size() > 0){
 //broadcast intent
}else{
 //post notification
}

Edit: Since this does not work on recievers registered through activites, you could track the register and unregister using Application class. Since same application and process is being used, you can make helper functtion to register and unregister and keep a count of registration and decide whether to post notification or broadcast an intent

于 2012-09-15T20:56:36.733 回答