避免从 WorkManager 复制 PeriodicWorkRequest [英] Avoiding duplicating PeriodicWorkRequest from WorkManager

查看:30
本文介绍了避免从 WorkManager 复制 PeriodicWorkRequest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在应用程序启动时,我想启动将永远工作的服务,但是当用户再次打开应用程序时,它会重复.

On Application start I want to start service that will work forever, but when user opens app again it duplicates.

PeriodicWorkRequest.Builder sendDataBuilder = new PeriodicWorkRequest.Builder(SendConnectionMetricsWorker.class, Constants.REPEAT_TIME_INTERVAL_IN_HOURS, Constants.REPEAT_TIME_INTERVAL_UNITS)
                .setConstraints(new Constraints.Builder()
                        .setRequiredNetworkType(NetworkType.CONNECTED)
                        .build());
        PeriodicWorkRequest periodicWorkRequest = sendDataBuilder
                .build();
        WorkManager.getInstance().enqueue(periodicWorkRequest);

推荐答案

您可以使用 enqueueUniquePeriodicWork 而不是 enqueue.基于文档:

You can use enqueueUniquePeriodicWork instead of enqueue. Based on the documentation:

此方法允许您将唯一命名的PeriodicWorkRequest,其中只有一个 PeriodicWorkRequest特定名称可以一次处于活动状态.例如,您可能只想要一个同步操作处于活动状态.如果有一个待处理,你可以选择让它运行或用您的新工作替换它.这uniqueWorkName 唯一标识此 PeriodicWorkRequest.

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. The uniqueWorkName uniquely identifies this PeriodicWorkRequest.

您可以通过以下方式实现:

You can achieve it as follows:

PeriodicWorkRequest.Builder sendDataBuilder = new PeriodicWorkRequest.Builder(SendConnectionMetricsWorker.class, Constants.REPEAT_TIME_INTERVAL_IN_HOURS, Constants.REPEAT_TIME_INTERVAL_UNITS)
                .setConstraints(new Constraints.Builder()
                        .setRequiredNetworkType(NetworkType.CONNECTED)
                        .build());
 PeriodicWorkRequest periodicWorkRequest = sendDataBuilder
                .build();
 WorkManager.getInstance().enqueueUniquePeriodicWork("Send Data",  ExistingPeriodicWorkPolicy.KEEP,periodicWorkRequest);

注意:

ExistingPeriodicWorkPolicy.REPLACE 确保如果有标记为 uniqueWorkName 的待处理工作,它将被取消并运行新工作.ExistingPeriodicWorkPolicy.KEEP 仅在没有标记为 uniqueWorkName 的待处理工作时才会运行新的 PeriodicWorkRequest.

ExistingPeriodicWorkPolicy.REPLACE ensures that if there is pending work labelled with uniqueWorkName, it will be cancelled and the new work will run. ExistingPeriodicWorkPolicy.KEEP will run the new PeriodicWorkRequest only if there is no pending work labelled with uniqueWorkName.

这篇关于避免从 WorkManager 复制 PeriodicWorkRequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆