问题描述
这是我的警报管理器代码:
This is my code for alarm manager:
Intent intent=new Intent(getBaseContext(),AlarmReciever.class);
intent.setAction("com.example.projectx.ACTION");
PendingIntent pendingIntent=PendingIntent.getBroadcast(this,12345, intent,PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager=(AlarmManager)getSystemService(Activity.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP,targetCal.getTimeInMillis(),pendingIntent);
如果我选择了在未来一小时/分钟触发的闹钟,此代码将非常有用。但是,如果我选择了过去的一个小时/分钟,则当我单击设置警报时,它会立即启动。
The code works great if i select the alarm to fire off at a future hour/minute. But if I select a past hour/minute it fires up immediately as I click on "set alarm".
示例:
-
现在是15:00,我将闹钟设置为15:45,闹钟在15:45响起,一切正常
now it is 15:00 , i set the alarm for 15:45, alarm goes off at 15:45, everything ok
现在是15:00,我将闹钟设置为14:30,只要单击设置闹钟,闹钟就会响起!
now it is 15:00 , i set the alarm for 14:30, the alarm goes off as soon as i click "set alarm"!
我的时间选择器始终设置为24小时模式。
My time picker is always set to 24 hour mode. Could that be a problem?
谢谢!
推荐答案
当然可以了。它应该是这样工作的。
Android意识到时间已经过去了,因此即使时间晚了,也会发出警报。
Of course it does... It's meant to work so.
Android recognizes that the time is past, so it will fire the alarm, even if it's late.
您可以确保为闹钟设置的时间在当前时间之后。
只需计算此差异即可:
You can make sure that the time set for the alarm is after the current time.Just calculate this difference:
int diff = Calendar.getInstance().getTimeInMilis() - targetCal.getTimeInMillis();
如果差异大于0,则在日历中添加一天(targetCal)
现在,您设备的时间将比下一个排定的闹钟时间更早(而不是更早)。
If diff is greater than 0, then add a day to your calendar (targetCal)
Now, your device's time will be earlier (instead of being later) than the next scheduled alarm time.
这篇关于Android:AlarmManager在过去的时间里触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!