我正在开发一个使用 AlarmManager 在后台生成一些服务的应用程序。时间对我们的应用程序非常重要,功能不能等待下一个维护窗口出现。 要求用户将应用程序列入白名单不是问题,但不能解决暂停警报的问题。电池消耗也不是什么大问题。
我想到的第一个可能的解决方案是生成一个始终运行的前台服务来处理服务的重新安排,而不是 AlarmManager,但这样做会改变我们应用程序的大部分基本结构,这对我们来说是不可行的。
我刚刚实现的当前修复是发送高优先级推送通知,并在收到消息后,采取完全唤醒锁定并打开屏幕以打破打瞌睡模式。
我想知道是否有其他方法可以打破打瞌睡模式?也可以不使用唤醒锁吗?实现上述解决方案可能会产生一些影响吗?
附言我正在使用 UrbanAirship 进行推送通知。
最佳答案
您无法“中断”/停止/禁用打瞌睡模式,但有一些方法可以在设备打瞌睡时暂时解除应用的限制。
- 高优先级 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.
- 使用 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 秒。
关于android - 打瞌睡模式处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41485308/