如何同时拥有同一广播 运行 的多个实例

How to have more than one instance of the same broadcast running simultaneously

我已经被困了 3 天了,要么我想做的事情非常基础,要么非常复杂,因为我似乎无法在任何地方找到答案。我有一个 BroadcastReceiver 和一个发送开始广播的意图的按钮,每次我单击它发送不同数据(int++)的按钮,意图有一个 10m 的计时器,所以我有两个问题:

1: 要发送数据,我必须使用 sendBroadcast(intent) 但要设置计时器,我必须使用 AlarmManager,并将数据放入意图中AlarmManager 的意图使其始终发送插入的第一个数据,我该如何解决这个问题?

2: 我想要同一个 BroadcastReceiver 的多个实例,同时 Alarms 计数而不会相互干扰。案例示例:用户创建了 1 个警报,5 分钟后他创建了另一个警报,发生的事情是在他设置第二个警报后 10 米只执行一个警报,覆盖第一个警报,预期结果是在他设置后 10 米执行第一个警报第一个并在他设置第二个后执行第二个,我该如何实现?

我的广播接收器:

public class Broadcast_RemoveClass extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            int i = intent.getExtras().getInt("mInt");
            Toast.makeText(context, "done"+i, Toast.LENGTH_LONG).show();
        }
    }

在 onClick 中发送意图:

public void startAlert(int i) {
    Intent intent = new Intent(getActivity(), Broadcast_RemoveClass.class);
    Bundle bd = new Bundle();
    bd.putInt("mInt", i);
    intent.putExtras(bd);
    // getActivity().sendBroadcast(intent);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity().getApplicationContext(), 0, intent, 0);
    AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 1000 * 60 * 10, pendingIntent);
    Toast.makeText(getActivity(), "countdown started " ,Toast.LENGTH_SHORT).show();
}

伙计们请帮忙,即使只是其中一个问题

当你这样做时:

PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity().getApplicationContext(), 0, intent, 0);

第一个 0 充当此待定意图的 ID。这样您就可以取消它或在将来更新它。如果您向系统发送另一个具有相同 ID(和适当标志)的未决意图,它将替换前一个。因此 post 您使用不同 ID 的新待处理意向。您对所有情况都使用硬编码 0....

此行为也由 end.You 中设置的标志控制,已将此值设置为 0。这毫无意义...PendingIntent 中没有 public static final 字段class 值为 0。切勿对标志使用硬编码值。即使它们具有有效值,它们也会使您的代码极其混乱。根据您要执行的操作,将最后的 0 替换为适当的标志。 PendingIntent class 中的可用标志是:

int FLAG_CANCEL_CURRENT
Flag indicating that if the described PendingIntent already exists, the current one should be canceled before generating a new one.
int FLAG_IMMUTABLE
Flag indicating that the created PendingIntent should be immutable.
int FLAG_NO_CREATE
Flag indicating that if the described PendingIntent does not already exist, then simply return null instead of creating it.
int FLAG_ONE_SHOT
Flag indicating that this PendingIntent can be used only once.
int FLAG_UPDATE_CURRENT
Flag indicating that if the described PendingIntent already exists, then keep it but replace its extra data with what is in this new Intent.

您不需要广播接收器的第二个实例。同一个广播接收器可以处理你想要的所有意图。