Search code examples
androidcalendaralarmmanager

AlarmManager doesn't starts at the right time even when the clock matches the time


I'm trying to make an app that should start every day at 17 o’clock. If I use "calendar.set ()" and lets say its 18 o´clock the alarm starts immediately after I set it. In the other hand if I use "calendar.add ()" it does not work, I mean even when the device clock matches the value that I set, for example, 17 o´clock, the alarm does not start at all.

     Calendar calendar = Calendar.getInstance();

 //calendar.add(Calendar.HOUR_OF_DAY, 17);
 //calendar.add(Calendar.MINUTE, 0);
 //calendar.add(Calendar.SECOND, 0);

 calendar.set(Calendar.HOUR_OF_DAY, 17);
 calendar.set(Calendar.MINUTE, 0);
 calendar.set(Calendar.SECOND, 0);

 Intent intent = new Intent(this, MyBroadcastReceiver.class);

    PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 123, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); 
    alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);

What I'm missing here? Thanks


Solution

  • You need to increase the DAY_OF_YEAR field by one if the current time is past 17:00.

    Calendar.getInstance() instantiates a new Calendar object using the current time. Let's pretend when this line is executed it's 18:00 on July 1st. After you set the hours, minutes, and seconds, the calendar now stores 17:00 on July 1st. When you set the alarm, AlarmManager sees this time is in the past and fires the alarm immediately.