安卓。警报管理器在奇怪的时间触发

标签 android performance alarmmanager alarm

我使用以下代码设置重复闹钟(每 5 分钟一次)。

public void SetAlarm(Context context)
{
     AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
     Intent i = new Intent(context, Alarm.class);
     PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
     am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 5, pi); // Millisec * Second * Minute
 }

似乎工作正常(它运行了将近 20 小时),并且在服务器中我可以看到一些持续的消息到达。

然而,时代有一些东西: 我希望时间是每五分钟一次,而且在服务器中我似乎在不同的时间收到消息。

当手机处于 sleep 模式(夜间)时,我添加服务器收到消息的第一个时间序列:

05:13:51,
05:18:54,
05:24:54,
05:28:54,
05:33:51,
05:38:54,
05:52:45,
05:54:54,
05:58:52,
06:04:54,
06:08:54,
06:16:19,
06:18:54,
06:24:54,
06:28:54,
06:34:54,
06:48:42,
06:48:44,
06:58:54,

还有我不时使用手机时的另一个序列:

11:08:46,
11:13:45,
11:18:48,
11:23:52,
11:33:54,
11:38:47,
11:48:47,
11:58:47,
12:03:52,
12:08:45,
12:14:49,
12:18:43,
12:25:37,
12:28:41,
12:34:56,
12:38:47,
12:43:48,
12:48:56,
12:54:07,
12:58:48,
13:03:43,
13:08:56,
13:14:11,
13:18:55,
13:25:02,
13:28:45,
13:33:43,
13:44:57,
13:48:58,
13:54:57,
13:58:52,
14:03:58

我注意到三种不同的异常情况:

  1. 跳过警报(例如服务器中两条消息之间的间隔为 10 分钟)- 我觉得没问题,可能是由于连接问题。

  2. 两条消息之间间隔 6 分钟,然后间隔 4 分钟的模式。您可以多次看到这种模式。我有一个假设,操作系统做了一些优化,例如,如果它每两分钟有一次其他警报(例如检查是否有新电子邮件),它会一起运行它们(并且 radio 只打开一次而不是二)。

  3. 奇怪的间隔(我无法解释它们)- 你可以看到。

所以我的问题:

  1. 如何强制系统每 5 分钟运行一次(或更加努力地运行一次)?

  2. 时间异常的原因是什么?我写了我的想法,但这些只是想法。

谢谢!

最佳答案

来自 API ( here ):

Note: 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.

因此,如果您使用的是 API 19,那么回答您的两个问题...

关于安卓。警报管理器在奇怪的时间触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20352210/

相关文章:

Android 应用程序 - 在 Google Play 上未找到 native 库错误报告?

mysql - 为什么 MySQL InnoDB 日志文件会产生如此大的 HDD 负载?

performance - 如何测量数据流任务中不同任务的持续时间?

java - java核心中文字操作和整数操作之间的性能问题

android - AlarmManager 与唤醒

android - 从数组列表中设置抽屉项目并在 MaterialDrawer 中单击

android - 如何管理自定义首选项布局

android - 尝试学习如何使用 Intent 和广播来终止我的应用程序。为什么它不死呢?

Android:从另一个 Activity 中取消闹钟设置

android - 如何使用 monkeyrunner(Python 脚本)启动 Activity "ACTION_SYNC_SETTINGS"或 "ACTION_ADD_ACCOUNT"