来自的DatePicker和TimePicker设置AlarmManagerDatePicker、TimePicker、AlarmManager

2023-09-06 16:27:08 作者:风光背后不

我很卡住创建从一个datepicker和TimePicker ...

I'm very stuck creating an alarm from a DatePicker and TimePicker...

这是我尝试的code:

This is the code of my try:

Calendar cal=Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, datePicker.getDayOfMonth());
cal.set(Calendar.MONTH, datePicker.getMonth());
cal.set(Calendar.YEAR, datePicker.getYear());
cal.set(Calendar.HOUR, timePicker.getCurrentHour());
cal.set(Calendar.MINUTE, timePicker.getCurrentMinute());        
long millis=cal.getTimeInMillis();

Intent intent=new Intent(CalendarView.this,AvisoReceiver.class);
PendingIntent mAlarmSender=PendingIntent.getBroadcast(CalendarView.this,23454546, intent,0);
AlarmManager alm=(AlarmManager)getSystemService(ALARM_SERVICE);
alm.set(AlarmManager.RTC_WAKEUP, millis,mAlarmSender);      

但是,当我把我的闹钟从TimePicker和DatePicker的我的接收器不叫。

But when I set my alarm from TimePicker and DatePicker my receiver isn't called.

如果我把我的报警接收器被调用,我让我的通知后3秒。

If I set my alarm 3 seconds after the receiver is called and I get my notification.

推荐答案

重写

因此​​,在凌晨2点编程的时候,我并不总是在我的巅峰。这里有两个修正案,添加到您的code,让你期望的行为(24/7):

So when programming at 2am I am not always at the top of my game. Here are two amendments to add to your code to get the behavior you expect (24/7):

cal.set(Calendar.HOUR_OF_DAY, timePicker.getCurrentHour());
cal.set(Calendar.SECOND, 0);

使用 HOUR_OF_DAY 阅读24小时的时间和第二个第二个设置为:00。在一小时只读取12小时的时间,这就是为什么在凌晨2点的工作不晚7点,为什么它是43000秒关(12小时)。如果没有设置第二个 Calendar对象将在第二承载电流分钟,创造出意想不到的延迟。

Use HOUR_OF_DAY to read 24hr time and SECOND to set the second to :00. The HOUR only reads 12hr time, this is why it worked at 2am not 7pm and why it was 43000 second off (12hr). Without setting SECOND the Calendar object it will carry the current minutes second over, creating an unexpected delay.

作为一个方面说明,还可以设置所有的日历值一次:

As a side note, you can also set all of the Calendar values at once:

cal.set(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth(), timePicker.getCurrentHour(), timePicker.getCurrentMinute(), 0);

无论采用哪种方法,都需要调用的是:

Whichever way, all you need to call is:

alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), mAlarmSender);      

(不,更看中的数学必要像我的第一个建议。)希望这有助于!

(No, more fancy math necessary like my first suggestion.) Hope this helps!