Search code examples
androidalarmmanagerandroid-alarms

AlarmManager triggers as soon as set


I am trying to trigger action everyday at 00:00:00 AM using AlarmManager but the problem is first time action is triggered quickly and then works as expected. First time, action triggers as soon as the code is run. Please see the following code:

private void setAlarmManagerForDateChange()
    {
        Intent intent = new Intent(this, DateTimeChangeReceiver.class);
        intent.putParcelableArrayListExtra("names", names);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this,
                999, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());

        calendar.set(Calendar.HOUR, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.AM_PM, Calendar.AM);

        AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(),
                24 * 60 * 60 * 1000, pendingIntent);
    }

It action triggers before 00:00:00 AM for the first time. Please point out what is being missed. Thanks,


Solution

  • You're scheduling the alarm in the past, which causes the AlarmManager to fire instantly.

    You take the current date (e.g. 05/29/14 20:08:32), and set the hour, minute and second to 0.
    What you get is: 05/29/14 00:00:00.

    What you actually want, is to add another day to get to 06/29/14 00:00:00.

    calendar.add(Calendar.DAY, 1);