android - setAlarmClock() 在打瞌睡模式下触发得太晚

标签 android alarmmanager sleep doze

我很难让我的 radio 闹钟按预期工作,我在这里阅读了很多关于该主题的帖子,但不幸的是没有一个对我有帮助。

AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);        
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent penInt = PendingIntent.getBroadcast(this, intentId, intent, 0);

我在 stackoverflow 上找到的这种区分 API 级别的方法并将其放入我的 calcNextAlarm() 函数(加上一些用于调试的日志消息)以正确设置警报,无论 API 是什么在设备上使用:

// problems in doze mode api 23+
if (Build.VERSION.SDK_INT >= 23) {
    if (testMode) Log.d("Ben", "setAlarmClock() - API 23+");
    am.setAlarmClock(new AlarmManager.AlarmClockInfo(alarmTimeInMillis, penInt), penInt);
}

else if (Build.VERSION.SDK_INT >= 19) {
// Wakes up the device in Idle Mode
    if (testMode) Log.d("Ben", "setExact() - API >= 19 && API < 23");
    am.setExact(AlarmManager.RTC_WAKEUP, alarmTimeInMillis, penInt);
}
// Old APIs
else {
    if (testMode) Log.d("Ben", "set() - API < 19");
    am.set(AlarmManager.RTC_WAKEUP, alarmTimeInMillis, penInt);
}

根据 Log.d 消息,我可以看到,在我的 Android 7.1 设备上,正在执行第一个方法 setAlarmClock() 以在 Receiver 中设置闹钟。

经过 3 周的不成功测试和编码后,我真的很绝望 - 今天我的闹钟再次晚了 4 分钟 - 根据打瞌睡模式培训页面,这永远不应该发生:

Alarms set with setAlarmClock() continue to fire normally — the system exits Doze shortly before those alarms fire.

在我的 7.1 手机上,当我将闹钟设置为“现在 +5 或 6”分钟时,闹钟甚至会延迟 20 秒到 1:40 分钟。谁能告诉我如何真正始终及时完美地关闭闹钟?

最佳答案

尝试使用:

setExactAndAllowWhileIdle()

这将确保警报按时触发。我已经在我自己的应用程序中对其进行了测试,它是可靠的。

如果您的目标 API 小于 23,请将其保留在 if 子句中,该子句检查设备中安装的当前 api。仅在 API 级别 23 以上使用此功能,其余请继续使用 setExact

可以回答您的评论:

1) 我已经在没有插入电池的情况下在打瞌睡模式下准确地测试了它

2) 是的,不幸的是,对于空闲类型的警报,每 9 分钟限制一次警报。这里有两种选择:

首先使用 setExactAndAllowWhileIdle 触发第一个警报。

a) 对于贪睡,你必须使用 setAlarmClock 方法

b) 对于贪睡,您可以安排一个 JobScheduler 作业,将最短延迟时间设置为您的贪睡时间。这将确保作业至少在贪睡间隔的间隙得到安排。但这会导致作业在间隔后随机安排,因此您还需要将覆盖截止日期设置为 0,以便在最小延迟后立即安排作业。还要将网络要求保持为无,并将需要的空闲模式保持为默认值或 false。根据我的经验,这也与警报精确方法一样可靠,我个人使用这种方法。

关于android - setAlarmClock() 在打瞌睡模式下触发得太晚,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48008999/

相关文章:

javascript - 从 React native 应用程序打开外部应用程序(单击按钮)

android - 位图不完全适合android中的矩形

android - 错误 :Binary XML file line : Inflating class fragment

android - 警报没有停止

java - 在 Android 中监控电池电量的正确优化方法

node.js - nodejs延迟执行redis命令

Android - 让进度条平稳增加,而不是跳得更大。

Android 重启广播接收器后未运行

c - 当线程处于 sleep 状态并且需要优雅地关闭时,使用 pthread_join、pthread_exit 或 pthread_cancel 做什么?

python - python 中的多线程 : when does a thread become inactive?