StarDust
StarDust

Reputation: 855

Android repeating alarm (AlarmManager.INTERVAL_DAY)

I am trying to implement a daily alarm.

    Intent intent = new Intent(mActivity, AlarmReceiver.class);
    intent.putExtra("weekdays", weekdays);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(mActivity.getApplicationContext(), weekdays ? WEEKDAYS_ID : WEEKENDS_ID, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    Calendar current = Calendar.getInstance();
    time.set(Calendar.SECOND, 0); // time a type of Calendar object which is set from TimePicker
    long timeDifference = time.getTimeInMillis() - current.getTimeInMillis();
    long triggerAt = (timeDifference > 0 ? time.getTimeInMillis() : AlarmManager.INTERVAL_DAY + timeDifference);
    mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, triggerAt, AlarmManager.INTERVAL_DAY, pendingIntent);

It works fine if I set a time in future. But if the time difference is negative (current time- 8:00, picked time- 7:45), the repeating alarm is set instantly and the broadcast receiver is fired! Though I have added AlarmManager.INTERVAL_DAY with the timeDifference to set it after a day, it isn't working.

Also, The AlarmManager.INTERVAL_DAY value is (86400000) which is smaller than the current time in milis (1387869223432), so adding it doesn't make much difference!

What am I missing here?

Ok, this is not working.

long triggerAt = (timeDifference > 0 ? time.getTimeInMillis() : time.getTimeInMillis() + AlarmManager.INTERVAL_DAY + timeDifference);

After debugging, I found that if I set earlier time, then add one day time - difference then the trigger time gets lower than the current time!

Alarm time: 1388073636969 (8am) current time: 1388130756977 (11:50pm)
Difference: -57120008
Alarm to be Triggered: 1388102916961
 // its alarm time (8am) + one day interval (1 day) -difference (4hr)

How come trigger time gets smaller than current time??

Upvotes: 0

Views: 2212

Answers (1)

Sudhee
Sudhee

Reputation: 714

You should add currentTimeInMillis too

current.getTimeInMillis() + AlarmManager.INTERVAL_DAY + timeDifference

If timeDifference is -15 minutes, the above statement will add-up to, current time + 24 hours - 15 minutes, which is what you want I presume.

AlarmManager.INTERVAL_DAY : Available inexact recurrence interval recognized by setInexactRepeating(int, long, long, PendingIntent) when running on Android prior to API 19.

Upvotes: 1

Related Questions