AlarmMamanger 不准确
AlarmMamanger not accurate
我的应用程序有一个 AlarmManager 设置为每 60 秒触发一次。它会触发一个片段,该片段会检查当前时间并在应用程序的日历中查找当时是否有任何事件发生。
运行 非常好,直到我发现它跳过了其中一个事件。为了检查应用程序的完整性,我让片段在文本文件上写入当前时间(0-59 分钟),看看它是否跳过任何时间。仔细翻看连续三天记录的文件,我发现确实如此。
47, 48, 50, 50, 51, 52, 54, 54, 55, 56, 57, 58, 59, 0, 1, 2,
这在任何地方都是随机发生的。它发生在 3-4 小时后。这是另一个例子
1, 1, 3, 4, 5, 6, 7, 7, 9, 9, 10, 11, 12, 13,
AlarmManager 代码看起来没有任何问题。尽管如果代码在给定时间过去之前跳过一分钟或触发,则某处有问题。
这是我在 AlarmManager
上使用的代码
long alertTime = new GregorianCalendar().getTimeInMillis();
int timeInterval = 60*1000;
Intent alertIntent = new Intent(this, AlertRec.class);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, alertTime, timeInterval, PendingIntent.getBroadcast(this, 1, alertIntent, PendingIntent.FLAG_UPDATE_CURRENT));
问题:
1) 为什么AlarmManager 行为异常?
2) 如何避免这种情况?
我可以减少间隔时间来解决这个问题吗?我读到 60 是您需要申请的最小间隔。
根据此处的文档:http://developer.android.com/reference/android/app/AlarmManager.html
Beginning with API 19 (KITKAT) alarm delivery is inexact: the OS will
shift alarms in order to minimize wakeups and battery use. There are
new APIs to support applications which need strict delivery
guarantees; see setWindow(int, long, long, PendingIntent) and
setExact(int, long, PendingIntent). Applications whose
targetSdkVersion is earlier than API 19 will continue to see the
previous behavior in which all alarms are delivered exactly when
requested.
这几乎解释了大部分内容。另外,据我所知,他们在内部添加了重复警报的最短时间限制 ~1 分钟,因此减少间隔可能不是最好的主意。
希望对您有所帮助!
我的应用程序有一个 AlarmManager 设置为每 60 秒触发一次。它会触发一个片段,该片段会检查当前时间并在应用程序的日历中查找当时是否有任何事件发生。 运行 非常好,直到我发现它跳过了其中一个事件。为了检查应用程序的完整性,我让片段在文本文件上写入当前时间(0-59 分钟),看看它是否跳过任何时间。仔细翻看连续三天记录的文件,我发现确实如此。
47, 48, 50, 50, 51, 52, 54, 54, 55, 56, 57, 58, 59, 0, 1, 2,
这在任何地方都是随机发生的。它发生在 3-4 小时后。这是另一个例子
1, 1, 3, 4, 5, 6, 7, 7, 9, 9, 10, 11, 12, 13,
AlarmManager 代码看起来没有任何问题。尽管如果代码在给定时间过去之前跳过一分钟或触发,则某处有问题。 这是我在 AlarmManager
上使用的代码long alertTime = new GregorianCalendar().getTimeInMillis();
int timeInterval = 60*1000;
Intent alertIntent = new Intent(this, AlertRec.class);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, alertTime, timeInterval, PendingIntent.getBroadcast(this, 1, alertIntent, PendingIntent.FLAG_UPDATE_CURRENT));
问题: 1) 为什么AlarmManager 行为异常? 2) 如何避免这种情况?
我可以减少间隔时间来解决这个问题吗?我读到 60 是您需要申请的最小间隔。
根据此处的文档:http://developer.android.com/reference/android/app/AlarmManager.html
Beginning with API 19 (KITKAT) alarm delivery is inexact: the OS will shift alarms in order to minimize wakeups and battery use. There are new APIs to support applications which need strict delivery guarantees; see setWindow(int, long, long, PendingIntent) and setExact(int, long, PendingIntent). Applications whose targetSdkVersion is earlier than API 19 will continue to see the previous behavior in which all alarms are delivered exactly when requested.
这几乎解释了大部分内容。另外,据我所知,他们在内部添加了重复警报的最短时间限制 ~1 分钟,因此减少间隔可能不是最好的主意。
希望对您有所帮助!