使用哪个TAG取消作业

时间:2019-05-28 12:32:49

标签: android-workmanager

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

1 个答案:

答案 0 :(得分:1)

PeriodicWorkRequest.BuilderOneTimeWorkRequest.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");

有关文档的更多信息,请参见: