gpt4 book ai didi

用于在后台运行日常任务的 Android WorkManager api

转载 作者:可可西里 更新时间:2023-11-01 19:09:53 24 4
gpt4 key购买 nike

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

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

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

但此后第一次打开应用程序时,它会重复运行 11 次,24 小时后不再运行。请任何人帮助我解决。

最佳答案

如果您想确保您的PeriodicWorkRequest 不会被多次创建,您可以使用WorkManager.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.


例如:

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,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50415756/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com