我实现了计划工作管理器。我的想法是每2小时完成一个过程。但我需要有保证的执行。根据 Work Manager 的文档,每个排队的进程都将得到执行。
但现在这个 setRequiresDeviceIdle 让我感到困惑。文档中指出,默认情况下 setRequiresDeviceIdle 已设置为 false。因此,我假设如果设备处于空闲模式,我的进程将无法运行。
空闲模式 = 当手机屏幕关闭一段时间。
但如果我将此 setRequiresDeviceIdle 设置为 true。我假设现在它只会在设备处于空闲模式时工作。
即使设备处于空闲或非空闲状态,我也希望进程能够完成。我现在该怎么办?
最佳答案
如果你通过 WorkManager Docs ,你会发现:
requiresDeviceIdle boolean: true if device must be idle for the work to run
如果您传递true
,则意味着您的工作将仅在设备处于空闲状态
时执行。
正如您提到的,您希望始终执行您的任务。因此,您应该在 setRequiresDeviceIdle()
中传递 false
。
注意:您的任务不必恰好在 2 小时后执行。根据DOCS ,您的任务可能会推迟到下一个 maintenance window
。您的任务肯定会执行,但持续时间不会正好是 2 小时。可能不止于此。
In Doze mode, the system attempts to conserve battery by restricting apps' access to network and CPU-intensive services. It also prevents apps from accessing the network and defers their jobs, syncs, and standard alarms.
Periodically, the system exits Doze for a brief time to let apps complete their deferred activities. During this maintenance window, the system runs all pending syncs, jobs, and alarms, and lets apps access the network.
如果您不希望您的任务始终在准确的时间执行,您可以使用 Alarm Manager和 setExactAndAllowWhileIdle()
。 但不鼓励这种做法,因为它不利于电池性能。
关于android - WorkManager setRequiresDeviceIdle 令人困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54745805/