Question

I have an application with a RTC alarm. Currently I set the alarm to fire daily at 8:00AM. My problem is that when the alarm starts say at (4:00PM), it will consider the starting time (8AM) already in the past and hence will run.

I want the alarm to run only around 8:00AM, but if it is started late in the day, doesn't run. Any idea how?

Was it helpful?

Solution

I suggest you to use to calendar.add(Calendar.DAY_OF_YEAR, 1);

Study following code:

Calendar calendar = Calendar.getInstance();
// 9 AM 
calendar.add(Calendar.DAY_OF_YEAR, 1);   ///to avoid firing the alarm immediately
calendar.set(Calendar.HOUR_OF_DAY, 9);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
PendingIntent pi = PendingIntent.getService(context, 0,
            new Intent(context, MyClass.class),PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                                AlarmManager.INTERVAL_DAY, pi);

Original Source

OTHER TIPS

You are using setInexactRepeating or setRepeating, right? So to handle such situations just compare 2 times: current time in msecs and (8AM, current day) in msecs. If first time more than the second one, then you should trigger your alarm on (8AM, next day), if not - (8AM, current day).

In my case, I wanted the Alarm to fire in the current day if time is not already passed, so I needed to improve Lucifer's answer a little bit.

void setTheAlarm(int hour, int minute)
{
    SettingsData.TriggerTime triggerTime = common.settingsData.getDeviceParamInfo().getConnectionTime();

    Calendar calendar = Calendar.getInstance();

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


    if(System.currentTimeMillis() > calendar.getTimeInMillis())
    {
        calendar.add(Calendar.DAY_OF_YEAR, 1);   ///to avoid firing the alarm immediately
    }

    // With setInexactRepeating(), you have to use one of the AlarmManager interval
    // constants--in this case, AlarmManager.INTERVAL_DAY.
    alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
            AlarmManager.INTERVAL_DAY, alarmIntent);

    Log.i("setTheAlarm", String.format("Alarm is set to %02d:%02d", hour, minute));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top