简体   繁体   English

对AlarmManager.setRepeating()的第二次调用在错误的时间传递

[英]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. 问题在于,每15分钟调用一次LowStockReceiver.onReceive() (如IntakeReceiver.onReceive() ),但仅应从11:50开始每小时调用一次。

I have checked the value of nowLastRounded + offset2 and it equals the local time today at 11:50 converted to GMT. 我检查了nowLastRounded + offset2的值,它等于今天当地时间11:50转换为GMT。 So it should run at 11:50, 12:50, 13:50, etc. (just for testing purposes currently). 因此,它应该在11:50、12:50、13:50等处运行(当前仅用于测试目的)。

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. 上面的代码在主Application类中被称为静态函数,可以通过第一个警报实例化。

  • 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. 这导致第二次警报被重新安排,时间似乎已经过去,导致立即被触发并使我感到困惑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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