Search code examples
javaandroidandroid-alarms

Set AlarmManager from DatePicker and TimePicker


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.


Solution

  • 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!