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