0

I want to create an alarm which will first fire at the next midnight and then repeat every midnight after.

Tried to calculate the time from now until midnight (in milliseconds) for the triggeratMillis parameter in the setRepeating() method (so the first alarm fires at the next midnight) but it is firing instantly as soon as it is created.

    private void resetAtMidnight() {
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);

    Intent intent = new Intent(getApplicationContext(), MidnightReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),
            MIDNIGHT_ALARM_ID, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
            calendar.getTimeInMillis()-System.currentTimeMillis(),
            AlarmManager.INTERVAL_DAY,
            pendingIntent);
}

I tried to make a calendar object initially set to the current dates midnight and then subtract the current time (in milliseconds) from the calendar midnight time.

Then I thought it might be thinking the midnight specified was the previous midnight so I tried to make it 11:59pm on the current day but this also did not work and the alarm fired instantly anyway.

jameshelou
  • 85
  • 1
  • 8
  • 1
    The `triggerAtMillis` parameter is the actual time to fire the first alarm, not the interval until then. Set your `Calendar` appropriately, and pass just `calendar.getTimeInMillis()`. [This post](http://stackoverflow.com/q/36535575) will likely be of some help to you, as well. – Mike M. May 07 '17 at 15:17

1 Answers1

0
public static long gettingNextMidnightTimeinMilliseconds() {
    Calendar c = Calendar.getInstance();
    c.set(Calendar.HOUR_OF_DAY, 0);
    c.set(Calendar.MINUTE, 0);
    c.set(Calendar.SECOND, 0);
    c.set(Calendar.MILLISECOND, 0);
    return c.getTimeInMillis() + (24 * 60 * 60 * 1000L);
}
Ashish
  • 183
  • 9