M Vignesh
M Vignesh

Reputation: 1646

How to avoid the alarm triggering when the alarm time is past?

I have scheduled an alarm to trigger on every day 10 AM.

I am setting this alarm at 12 AM Monday.

If the alarm time is past then the alarm will be triggered immediately.

but for my requirement I don't want to trigger immediately. Is fine for me to trigger on next day 10 AM.

Below is my current code to set Alarm:

Calendar activeModeTime = Calendar.getInstance();
    // activeModeTime.setTimeZone(TimeZone.getTimeZone(Constants.TIME_ZONE));
    activeModeTime.set(Calendar.HOUR_OF_DAY,
            mSharedPrefManager.getActiveStartHourPref());
    activeModeTime.set(Calendar.MINUTE,
            Constants.DEFAULT_ACTIVE_START_MINUTE);
    activeModeTime.set(Calendar.SECOND,
            Constants.ALL_START_END_DEFAULT_SECOND);

    mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
            activeModeTime.getTimeInMillis(), AlarmManager.INTERVAL_DAY,
            getActiveModeAlarmPendingIntent());

how do I achieve this.

Upvotes: 2

Views: 1404

Answers (2)

Prits Ramani
Prits Ramani

Reputation: 100

write interval instead of REPEATING_INTERVAL. For above example of 10 AM you need to write AlarmManager.INTERVAL_DAY instead of REPEATING_INTERVAL in below code.

if(Calendar.getInstance().getTimeInMillis()>=calendar.getTimeInMillis()){
   timeInMillis = calendar.getTimeInMillis() + REPEATING_INTERVAL;
}else { 
   timeInMillis = calendar.getTimeInMillis();
}

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, timeInMillis,REPEATING_INTERVAL, pendingIntent);

Upvotes: 0

rahul.taicho
rahul.taicho

Reputation: 1379

Check if the time that you've set is in the past and if it is then add 24 hrs to your trigger time.

if(activeModeTime < System.currentTimeMillis()){
    activeModeTime += AlarmManager.INTERVAL_DAY;
}

Upvotes: 5

Related Questions