问题描述
即使该应用已关闭,我也需要每天在后台调用一个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:
例如:
For example:
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,用于在后台运行日常任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!