本文介绍了Android Oreo workmanager PeriodicWork 不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

安卓版本:8.1.0

设备:Infinix X604B

Device: Infinix X604B

Workmanager:1.0.0-alpha11(最新版本)

Workmanager: 1.0.0-alpha11 (latest version)

安排一个 PeriodicWorkRequest 在每 15 分钟后运行一次.工作请求每 15 分钟运行一次,持续大约一小时.然后 PeriodicWorkRequest 停止工作.在 8 小时内,根本没有安排后台工作.我没有杀死我的应用程序,它在后台.

Scheduled a PeriodicWorkRequest to run after every 15 minutes.Work request runs after every 15 minutes for approximately one hour. Then PeriodicWorkRequest stops working. In 8 hours the background work doesn't get scheduled at all. I have not killed my app, it is in the background.

当我将应用程序带回前台时,PeriodicWorkRequest 再次运行后台任务.有类似的经历,我把我的应用程序放在后台后不再重复.

When I bring the app back to foreground PeriodicWorkRequest runs the background task again. With similar experience no repetition after I put my app in the background.

我已为我的应用禁用电池优化.

I've disabled battery optimization for my app.

这是 My Worker 类示例.

Here is My Worker class sample.

class TestWorker extends Worker {
public TestWorker(
        @NonNull Context context,
        @NonNull WorkerParameters params) {
    super(context, params);
}

@NonNull
@Override
public Result doWork() {
    // Adding timestamp of background execution to firestore.
    Map<String, String> value = new TreeMap<>();
    SimpleDateFormat df = new SimpleDateFormat("hh:mm");
    String dateFormat = df.format(Calendar.getInstance().getTime());
    value.put("time", dateFormat);
    FirebaseFirestore.getInstance()
            .collection("my-collection")
            .add(value);
    return Result.SUCCESS;
}

}

我是这样称呼它的:

PeriodicWorkRequest.Builder testBuilder =
    new PeriodicWorkRequest.Builder(TestWorker.class, 15,
                                    TimeUnit.MINUTES);

PeriodicWorkRequest testWork = testBuilder.build();
WorkManager.getInstance().enqueue(testWork);

推荐答案

您可以从如下独特的周期性工作开始,

You can begin with unique periodic work like below,

WorkManager.getInstance().enqueueUniquePeriodicWork(UNIQUE_ID, ExistingPeriodicWorkPolicy.REPLACE, testWork);

这里,UNIQUE_IDString,它将检查您的工作人员的唯一性并替换现有工作人员(如果它已存在于定期工作队列中).

Here, UNIQUE_ID is String that will check for uniqueness of your worker and replace existing one if it's already exists in queue for periodic work.

此处查看工作人员政策.

Check out Worker policies here.

并且不要忘记将相同的标签添加到您的工作器实例中,例如:

And don't forget to add the same tag to your worker instance like:

PeriodicWorkRequest.Builder testBuilder =
new PeriodicWorkRequest.Builder(TestWorker.class, 15, TimeUnit.MINUTES);
PeriodicWorkRequest testWork = testBuilder.addTag(UNIQUE_ID).build(); // Set the same string tag for worker.

这篇关于Android Oreo workmanager PeriodicWork 不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 22:24