问题描述
在应用程序启动时,我想启动将永远工作的服务,但是当用户再次打开应用程序时,它会重复.
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.
您可以通过以下方式实现:
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!