其他分享
首页 > 其他分享> > 用于在后台运行日常任务的Android WorkManager api

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

作者:互联网

即使应用已关闭,我也需要在后台每天调用一个API.我见过有关WorkManager API的信息.对于我的场景,我尝试了PeriodicWorkRequest,但遗憾的是,它不能达到我预期的结果.我做的是我在Application类中使用了这段代码

 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,android-jetpack,android-workmanager,android-jobscheduler
来源: https://codeday.me/bug/20190928/1829756.html