spongyboss
spongyboss

Reputation: 8666

Schedule Android Background Operations

I am trying to execute a background process on my android app every day at around 09h10 am. This works fine, but problem is after the first alarm has been fired at 09h10 am, it gets re-fired after 10 - 20 minutes throughout the day. I just want it to fire once a day, and only at that specified time. My code that sets the alarm manager is below:

PendingIntent reviewsPendingIntent = PendingIntent.getBroadcast(this,0,new Intent(this,ReviewReceiver.class),0);
AlarmManager alarmManager = (AlarmManager)(this.getSystemService(Context.ALARM_SERVICE));

Calendar cur_cal = new GregorianCalendar();
cur_cal.setTimeInMillis(System.currentTimeMillis());

Calendar cal = new GregorianCalendar();
cal.set(Calendar.HOUR_OF_DAY, 9);
cal.set(Calendar.MINUTE, 10);
cal.set(Calendar.SECOND, 10);
cal.set(Calendar.MILLISECOND, cur_cal.get(Calendar.MILLISECOND));

long interval = 6000*1440;

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(),interval,reviewsPendingIntent);

I have set the interval to 8640000 which is a day(I believe) if not, please advise accordingly. Thank you

Upvotes: 0

Views: 61

Answers (3)

Lindus
Lindus

Reputation: 66

You can use

PendingIntent reviewsPendingIntent = PendingIntent.getBroadcast(this,0,new Intent(this,ReviewReceiver.class),PendingIntent.FLAG_CANCEL_CURRENT);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(),AlarmManager.INTERVAL_DAY,reviewsPendingIntent);

FLAG_CANCEL_CURRENT will prevent the alarm to be set multiple times AlarmManager.INTERVAL_DAY = 1000 * 60 * 60 * 24

Upvotes: 1

Viktor Yakunin
Viktor Yakunin

Reputation: 3266

1000ms*60s*60m*24h = 86400000 so You missed one 0

Upvotes: 1

Filnik
Filnik

Reputation: 138

If you keep having some delay, it's because the sleep function is not precise. It's around the time you have set. Try with setExact and reschedule every day, doing the math by hand (initialTime + dayPassed * millsInADay) to have the best approximation.

If what Lindus has posted worked though, just forget it :) but I think that you'll have the same problem.

Upvotes: 0

Related Questions