本文介绍了用于在后台运行日常任务的 Android WorkManager api的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即使应用程序关闭,我也需要每天在后台调用一个 API.我已经看到了 WorkManager API.对于我的场景,我尝试了 PeriodicWorkRequest 但不幸的是,它没有达到我的预期结果.我所做的是在 Application 类中使用了这段代码

I need to call one API daily in the background even if the app is closed. I have seen about WorkManager API. For my scenario, I tried PeriodicWorkRequest but unfortunately, it's not working as my expected result. What I did is I used this code in the Application class

 PeriodicWorkRequest.Builder myWorkBuilder =
                new PeriodicWorkRequest.Builder(MyWorker.class, 24,
                        TimeUnit.HOURS);

        PeriodicWorkRequest myWork = myWorkBuilder.build();
        WorkManager.getInstance().enqueue(myWork);

但是此后第一次打开该应用程序时它重复运行了11次,24小时后它没有运行.请任何人帮我解决.

But it's running repeatedly for 11 times when the app is open for the first time after that, it's not running after 24 hrs. Please, anyone, help me to solve.

推荐答案

如果您想确保您的 PeriodicWorkRequest 没有被多次创建,您可以使用 WorkManager.enqueueUniquePeriodicWork 方法来安排您的工作人员:

If you want to make sure your PeriodicWorkRequest is not created multiple times you can use the WorkManager.enqueueUniquePeriodicWork method to schedule your worker:

此方法允许您将唯一命名的 PeriodicWorkRequest 加入队列,其中一次只能激活一个特定名称的 PeriodicWorkRequest.例如,您可能只想激活一个同步操作.如果有待处理,您可以选择让它运行或替换为您的新工作.

例如:

PeriodicWorkRequest.Builder myWorkBuilder =
            new PeriodicWorkRequest.Builder(MyWorker.class, 24, TimeUnit.HOURS);

PeriodicWorkRequest myWork = myWorkBuilder.build();
WorkManager.getInstance()
    .enqueueUniquePeriodicWork("jobTag", ExistingPeriodicWorkPolicy.KEEP, myWork);

这篇关于用于在后台运行日常任务的 Android WorkManager api的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 10:52