简体   繁体   中英

Second call to AlarmManager.setRepeating() gets delivered at wrong time

My application executes the following code:

// Check intakes every 15 minutes
Intent i = new Intent(this, IntakeReceiver.class);
i.putExtra("TYPE", "TAKEIN_CHECK");
PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(), 0, i, 0);

AlarmManager am = (AlarmManager)(this.getSystemService(Context.ALARM_SERVICE));
Calendar cal = Calendar.getInstance();
int offset = 1000 * 60 * 15; // 1000 * 60 * 15 (15 minutes)
long nowLastRounded = cal.getTimeInMillis() - (cal.getTimeInMillis() % offset);
am.setRepeating(AlarmManager.RTC_WAKEUP, nowLastRounded + offset, offset, pi);

// Also set alarm for 11:50 every day to notify about low stock
Intent i2 = new Intent(this, LowStockReceiver.class);
i2.putExtra("TYPE", "STOCK_CHECK");
PendingIntent pi2 = PendingIntent.getBroadcast(getApplicationContext(), 1, i2, 0);

long interval_day = AlarmManager.INTERVAL_DAY;
long interval_hour = AlarmManager.INTERVAL_HOUR;
int offset2 = 1000 * 60 * 60 * 11 + 1000 * 60 * 50; // 11:50

final int tzOffset = TimeZone.getDefault().getOffset(System.currentTimeMillis());
offset2 -= tzOffset;

nowLastRounded = cal.getTimeInMillis() - (cal.getTimeInMillis() % interval_day);
am.setRepeating(AlarmManager.RTC_WAKEUP, nowLastRounded + offset2, interval_hour, pi2);

The problem is that the LowStockReceiver.onReceive() is called every 15 minutes (like the IntakeReceiver.onReceive() ) but it should only be called every hour starting from 11:50.

I have checked the value of nowLastRounded + offset2 and it equals the local time today at 11:50 converted to GMT. So it should run at 11:50, 12:50, 13:50, etc. (just for testing purposes currently).

Anyone have any idea what I could be doing wrong?

Thank you!

您对两个警报使用相同的ID作为待定意图。请使用不同的ID。

Solved my own problem.

The problem was two-fold but the question didn't contain enough details for the question to be solvable:

  • Above code was called as a static function from the main Application class which could get instantiated by the first alarm.

  • This caused the second alarm to be rescheduled, and the time appeared to be in the past, causing it to be fired immediately and confusing me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM