来自的DatePicker和TimePicker设置AlarmManager [英] Set AlarmManager from DatePicker and TimePicker

查看:217
本文介绍了来自的DatePicker和TimePicker设置AlarmManager的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很卡住创建从一个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!

这篇关于来自的DatePicker和TimePicker设置AlarmManager的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆