Avoiding duplicating PeriodicWorkRequest from WorkManager

此生再无相见时 提交于 2019-12-21 13:02:23

问题


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);

回答1:


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

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);

Note:

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.



来源:https://stackoverflow.com/questions/50943056/avoiding-duplicating-periodicworkrequest-from-workmanager

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!