我有一个Android应用程序,我使用AlarmManager来安排一些重复的警报,我也有一个意图和一个广播接收器,所以当警报触发时它会执行广播接收器。
这是我如何设置闹钟
static Calendar GenerateSchedule(int Hour, int Minute)
{
Calendar now = Calendar.GetInstance(Java.Util.TimeZone.Default);
Calendar alarmTime = Calendar.GetInstance(Java.Util.TimeZone.Default);
alarmTime.Set(CalendarField.HourOfDay, Hour);
alarmTime.Set(CalendarField.Minute, Minute);
alarmTime.Set(CalendarField.Second, 0);
alarmTime.Set(CalendarField.Millisecond, 0);
return alarmTime;
}
public static void AddAlarm(int Id, int hour, int Minute)
{
var Manager = (AlarmManager)Application.Context.GetSystemService(Context.AlarmService);
Intent AlarmIntent = new Intent(Application.Context, typeof(AlarmNotificationReceiver));
AlarmIntent.PutExtra("Id", Id);
PendingIntent pendingIntent;
pendingIntent = PendingIntent.GetBroadcast(Application.Context, Id, AlarmIntent, PendingIntentFlags.UpdateCurrent);
if (pendingIntent != null)
{
Calendar Schedule = GenerateSchedule(hour, Minute);
Manager.SetRepeating(AlarmType.RtcWakeup, Schedule.TimeInMillis, AlarmManager.IntervalDay, pendingIntent);
}
}
这是对AddAlarm的调用
AddAlarm(0, 5, 30);
AddAlarm(1, 6, 30);
AddAlarm(2, 7, 30);
AddAlarm(3, 8, 30);
AddAlarm(4, 9, 30);
这是广播接收者
[BroadcastReceiver(Enabled = true)]
public class AlarmNotificationReceiver: BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
Toast.MakeText(context, "THIS IS MY ALARM", ToastLength.Long).Show();
}
}
因此,使用上面的代码,我在一天中的不同时间设置了5个警报。
我的期望是我的广播接收器每次报警会触发1次,但实际上每次5次报警中的任何一次触发广播接收器执行的次数与我预定的报警次数相同,所以在这种情况下会触发5次
我应该在BroadcastReceiver上做任何特殊代码来处理这种情况吗?或者我是否以错误的方式安排警报?