PeriodicWorkRequest.Builder has addTag
method, enqueueUniquePeriodicWork(TAG, policy, periodicWorkRequest)
also has the TAG.
Question is which TAG to use in order to cancel all MyWorker
task ? Will it be MyWorkerTag
or MySchedulerClassTag
PeriodicWorkRequest.Builder builder = new PeriodicWorkRequest.Builder(
MyWorker.class,
PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS,
TimeUnit.MILLISECONDS);
builder.addTag("MyWorkerTag");
WorkManager.getInstance().enqueueUniquePeriodicWork("MySchedulerClassTag", ExistingPeriodicWorkPolicy.KEEP, builder.build());
Both PeriodicWorkRequest.Builder
and OneTimeWorkRequest.Builder
include a addTag()
method that allows you to set a TAG
that you can later use to identify a set of work request to observe or cancel them.
In the case of the enqueueUniquePeriodicWork(UniqueName, policy, workrequest)
, the first parameters is a unique name used by WorkManager to identify each unique work and it is not related to the TAG
assigned to the WorkRequest.
So, to cancel your worker you should use the TAG
set on the WorkRequest using the setTag
method:
PeriodicWorkRequest.Builder builder = new PeriodicWorkRequest.Builder(
MyWorker.class,
PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS,
TimeUnit.MILLISECONDS)
.addTag("MyWorkerTag")
.build();
WorkManager.getInstance(context).enqueueUniquePeriodicWork(
"UniqueName",
ExistingPeriodicWorkPolicy.KEEP,
builder);
// Later on, when needed
WorkManager.getInstance(context).cancelAllWorkByTag("MyWorkerTag");
More information are available on the documentation: