Set AlarmManager from DatePicker and TimePicker

江枫思渺然 提交于 2019-12-08 06:33:54

问题


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

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);      

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

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


回答1:


Rewrite

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);

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!



来源:https://stackoverflow.com/questions/10569206/set-alarmmanager-from-datepicker-and-timepicker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!