PeriodicWorkRequest.Builder具有addTag
方法,enqueueUniquePeriodicWork(TAG, policy, periodicWorkRequest)
也具有TAG。
问题是使用哪个TAG来取消所有MyWorker
任务?是MyWorkerTag
还是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());
答案 0 :(得分:1)
PeriodicWorkRequest.Builder
和OneTimeWorkRequest.Builder
都包含[[addTag()
6方法,该方法允许您设置TAG
,以后可以用来标识一组工作要求观察或cancel。
对于enqueueUniquePeriodicWork(UniqueName, policy, workrequest)
,第一个参数是WorkManager用来标识每个唯一作品的唯一名称,它与分配给WorkRequest的TAG
不相关。
因此,要取消您的工作人员,您应使用TAG
方法使用在WorkRequest上设置的setTag
:
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");
有关文档的更多信息,请参见: