Android PeriodicWorkRequest Builder 如何避免重复调度?

Android PeriodicWorkRequestBuilder how to avoid double scheduling?

我正在使用新的 WorkManager,我想知道,当我安排定期工作时,如何避免重新安排它,它是由 OS 自动处理的吗?

它是一个周期性的 Worker,所以它会自动处理重新安排下一次事件。 为避免它是 re-scheduled,您可以从您的 Worker return Result.failed() 或您可以从您的应用取消 WorkRequest。在这种情况下,您应该按照 documentation.

中的说明在 Worker 中处理取消

如果您只是因为不想重复工作而需要检查 运行 工作管理器。您可以简单地使用 enqueueUniquePeriodicWork()

This method allows you to enqueue a uniquely-named PeriodicWorkRequest, where only one PeriodicWorkRequest of a particular name can be active at a time. For example, you may only want one sync operation to be active. If there is one pending, you can choose to let it run or replace it with your new work.

因此您无需担心作品重复。

 workmanager.enqueueUniquePeriodicWork(TAG, ExistingPeriodicWorkPolicy.KEEP , photoCheckWork);
  • 其中 TAG 是工作管理器用来检查重复项的唯一名称。
  • 您可以 choose between ExistingPeriodicWorkPolicy.KEEPExistingPeriodicWorkPolicy.REPLACE