以下是我从外部API提取数据时用于创建警报的代码。如果设置的时间是过去的,则一旦设置(2秒间隙),闹钟就会熄灭。例如,如果我将闹钟设置为4月11日上午8点,即4月11日上午10点(过去时间)。它会在设置完成后立即开始报警。
public static final int ALARM_REQUEST_CODE = 1001;
public static AlarmManager alarmManager = (AlarmManager) EHCApplication.getInstance().getApplicationContext().getSystemService(Context.ALARM_SERVICE);
public static Intent alarmIntent = new Intent(EHCApplication.getInstance().getApplicationContext(), AlarmReceiver.class);
public static PendingIntent pendingIntent = PendingIntent.getBroadcast(EHCApplication.getInstance().getApplicationContext(), ALARM_REQUEST_CODE, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
public static void setAlarm(Reminder rm) {
for (ScheduledTime time : rm.getScheduledTime()) {
Bundle bundle = new Bundle();
bundle.putParcelable(Constants.ARGS_SELECTED_MEDICINE, medicine);
alarmIntent.putExtras(bundle);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time.getTimeInMilliseconds(), AlarmManager.INTERVAL_DAY, pendingIntent);
}
}
我期待闹钟会在下次播出时播出。我在哪里弄错了?
答案 0 :(得分:2)
这是预期的行为。
来自setRepeating()
(以及其他AlarmManager
设置方法)的文档:
如果声明的触发时间是过去的,则会触发警报 立即
如果您希望防止这种情况发生,请不要设置过去触发时间的闹钟(例如,在设置闹钟时检查System.currentTimeMillis()
)。
答案 1 :(得分:0)
好吧,我遇到了同样的问题,经过研究,我发现警报会在警报设置过去的时间后立即运行。 资料来源:Here is documentation of Alarm Manager - setRepeating()
所以,我通过检查"日历时间是否超过系统时间而不是我添加一天来解决了这个问题"
工作代码:
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, min);
calendar.set(Calendar.SECOND, 0);
alarmManager.cancel(pendingIntent);
// Check if the Calendar time is in the past
if (calendar.getTimeInMillis() < System.currentTimeMillis()) {
Log.e("setAlarm","time is in past");
calendar.add(Calendar.DAY_OF_YEAR, 1); // it will tell to run to next day
}
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, id, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent); //Repeat every 24 hours