Search code examples
androidalarmmanager

Alarm using AlarmManager class only works for current day


I have a working alarm using the alarmManager class. If I set the alarm for any time before midnight of the current day everything is fine. If I want to set the alarm for the 7 a.m., however, and 7 a.m. has already come and gone for today, that of course does not work.

Is there a way to do this without implementing datepicker and dates into the program?

Below is a code sample. I can post more complete code if needed.

 Intent myIntent = new Intent(AlarmActivity.this, AlarmReceiver.class);
        pendingIntent = PendingIntent.getBroadcast(AlarmActivity.this, 0, myIntent, 0);

        repeatInterval = LoadPreferences("repeatInterval", repeatInterval);  //gets number of minutes reminder should repeat

        repeatIntervalMilliseconds = repeatInterval * 1000 * 60;  //converts repeating interval to milliseconds for setRepeating method

        //Set a one time alarm
        if (repeatInterval == 0) {
            alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
            AlarmReceiver alarmReceiver = new AlarmReceiver(this); //http://stackoverflow.com/questions/16678763/the-method-getapplicationcontext-is-undefined

            Toast.makeText(AlarmActivity.this, "Your one time reminder is now set for " + hourSet + ":" + minuteSetString + amPmlabel, Toast
                    .LENGTH_LONG)
                    .show();
        }

        //Set a repeating alarm
        else {
            alarmManager.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), repeatIntervalMilliseconds, pendingIntent);
            AlarmReceiver alarmReceiver = new AlarmReceiver(this); //http://stackoverflow.com/questions/16678763/the-method-getapplicationcontext-is-undefined

                Toast.makeText(AlarmActivity.this, "Your reminder is now set for " + hourSet + ":" + minuteSetString + amPmlabel + " and will " +
                        "repeat " +
                        "every " +
                        repeatInterval + " minutes.", Toast.LENGTH_LONG).show();

        }

Solution

  • I am testing this solution as recommended by Mike M. I will know tomorrow morning if this works. Mike if you want to post the same solution separately, and this is successful (and I think it will be), I can award you points.

     //Add 1 day to alarmTime if alarmTime has already gone by for today
               calendarComparison = now.compareTo(alarmTime);
               if (calendarComparison == 1){
                   alarmTime.add(Calendar.DATE, 1);
               }