Avoiding duplicating PeriodicWorkRequest from Work

2019-04-07 19:05发布

问题:

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.