android - 打瞌睡模式处理

标签 android android-6.0-marshmallow android-doze android-doze-and-standby

我正在开发一个使用 AlarmManager 在后台生成一些服务的应用程序。时间对我们的应用程序非常重要,功能不能等待下一个维护窗口出现。 要求用户将应用程序列入白名单不是问题,但不能解决暂停警报的问题。电池消耗也不是什么大问题。

我想到的第一个可能的解决方案是生成一个始终运行的前台服务来处理服务的重新安排,而不是 AlarmManager,但这样做会改变我们应用程序的大部分基本结构,这对我们来说是不可行的。

我刚刚实现的当前修复是发送高优先级推送通知,并在收到消息后,采取完全唤醒锁定并打开屏幕以打破打瞌睡模式。

我想知道是否有其他方法可以打破打瞌睡模式?也可以不使用唤醒锁吗?实现上述解决方案可能会产生一些影响吗?

附言我正在使用 UrbanAirship 进行推送通知。

最佳答案

您无法“中断”/停止/禁用打瞌睡模式,但有一些方法可以在设备打瞌睡时暂时解除应用的限制。

  1. 高优先级 FCM 消息。

FCM high-priority messages let you reliably wake your app to access the network, even if the user’s device is in Doze or the app is in App Standby mode. In Doze or App Standby mode, the system delivers the message and gives the app temporary access to network services and partial wakelocks, then returns the device or app to the idle state.

High-priority FCM messages do not otherwise affect Doze mode, and they don’t affect the state of any other app. This means that your app can use them to communicate efficiently while minimizing battery impacts across the system and device.

  1. 使用 AlarmManager 设置的 andAllowWhileIdle 警报。

Doze is particularly likely to affect activities that AlarmManager alarms and timers manage, because alarms in Android 5.1 (API level 22) or lower do not fire when the system is in Doze.

To help with scheduling alarms, Android 6.0 (API level 23) introduces two new AlarmManager methods: setAndAllowWhileIdle() and setExactAndAllowWhileIdle(). With these methods, you can set alarms that will fire even if the device is in Doze.

请注意,打瞌睡模式下两次警报之间的最短间隔为 9 分钟。


对于这两种情况,您的应用都会在短时间内恢复到全部功能(意味着:打盹限制不适用),当该时间到期时,操作系统将恢复打盹限制。

请注意,在这些“唤醒”期间,您无需打开屏幕即可执行代码。

我手边没有消息来源,但我相信我说的短时间约为 10 秒。

Source & additional reading

关于android - 打瞌睡模式处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41485308/

相关文章:

android - GET_ACCOUNTS 权限危险吗?

Android Nougat PhoneStateListener 未触发

Android DOZE 模式 GCM 优先级

android - 在打瞌睡模式下获取位置更新

android - 多次调用 FragmentTransaction.replace() - 只有一次在方向改变后有效

java - 如何将 R 资源数组设置为字符串数组

permissions - 从 Android M nexus 6 上的设置启用/禁用权限后,应用程序被杀死

java - 我无法将 Java 完美地转换为 Kotlin

android - 在 Dagger 中注入(inject)泛型

android - 在开发人员控制台中将 Android 目标 Api 级别 23 降级到 22