本文介绍了使用 WorkManager 定期提出日常工作请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何正确使用来自 Android Jetpack 的新 WorkManager 来安排每天一次的定期工作,该工作应该每天只做一次操作?

How to properly use the new WorkManager from Android Jetpack to schedule a one per day periodic work that should do some action on a daily basis and exactly one time?

我们的想法是使用 WorkManager 检查具有给定标签的工作是否已经存在,否则就开始新的定期工作.

The idea was to check if the work with a given tag already exists using WorkManager and to start a new periodic work otherwise.

我尝试使用下一种方法来做到这一点:

I've tried to do it using next approach:

public static final String CALL_INFO_WORKER = "Call worker";

...

WorkManager workManager = WorkManager.getInstance();
List<WorkStatus> value = workManager.getStatusesByTag(CALL_INFO_WORKER).getValue();
if (value == null) {
    WorkRequest callDataRequest = new PeriodicWorkRequest.Builder(CallInfoWorker.class,
                24, TimeUnit.HOURS, 3, TimeUnit.HOURS)
                .addTag(CALL_INFO_WORKER)
                .build();
    workManager.enqueue(callDataRequest);
}

但是 value 始终为 null,即使我在 WorkerdoWork() 方法中放置了一个断点(所以它是肯定在进行中)并从另一个线程检查工作状态.

But the value is always null, even if I put a breakpoint inside the Worker's doWork() method (so it is definitely in progress) and check the work status from another thread.

推荐答案

您现在可以使用 enqueueUniquePeriodicWork 方法.它是在 WorkManager 的 1.0.0-alpha03 版本中添加的.

You can now use enqueueUniquePeriodicWork method. It was added in 1.0.0-alpha03 release of the WorkManager.

这篇关于使用 WorkManager 定期提出日常工作请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 10:53