微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

用于在后台运行日常任务的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);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐