WorkManager.getInstance().cancelAllWorkByTag() not stopping the periodic job

PPD picture PPD · Sep 7, 2018 · Viewed 9.4k times · Source

for periodic task I am using work manager as:

PeriodicWorkRequest.Builder wifiWorkBuilder =
                            new PeriodicWorkRequest.Builder(FileUpload.class, 15,
                                    TimeUnit.MINUTES)
                                    .setConstraints(new Constraints.Builder().setRequiredNetworkType(NetworkType.METERED).build());
                    PeriodicWorkRequest wifiWork = wifiWorkBuilder.build();
                    WorkManager.getInstance().enqueueUniquePeriodicWork("wifiJob", ExistingPeriodicWorkPolicy.REPLACE, wifiWork);

I have one activity in that activity one check box is there if user unselect checkbox then I want to stop this job. So I am stopping job like:

WorkManager.getInstance().cancelAllWorkByTag("wifiJob");

But after stopping job also my task is executing. Previously I thought might be next job will be executed and after that it will stop but in last 1 hour it executed 4 times and still job is running in background. What is other way or correct way to stop job.

as per Docs:

Cancels all unfinished work with the given tag. Note that cancellation is a best-effort policy and work that is already executing may continue to run.

What is the meaning of this - cancellation is a best-effort policy and work that is already executing may continue to run. So what is the correct way to stop this

I am using version implementation "android.arch.work:work-runtime:1.0.0-alpha08" Thanks in advance

Answer

PPD picture PPD · Sep 10, 2018

While creating PeriodicWorkRequest i had added addTag() and to cancel task used same tag name, using this it cancel pending work. So my code is like:

PeriodicWorkRequest.Builder wifiWorkBuilder =
                            new PeriodicWorkRequest.Builder(FileUpload.class, 15,
                                    TimeUnit.MINUTES)
                                    .addTag("WIFIJOB1")
                                    .setConstraints(new Constraints.Builder().setRequiredNetworkType(NetworkType.METERED).build());
                    wifiWork = wifiWorkBuilder.build();
                    WorkManager.getInstance().enqueueUniquePeriodicWork("wifiJob", ExistingPeriodicWorkPolicy.REPLACE, wifiWork);

To stop job I am using:

WorkManager.getInstance().cancelAllWorkByTag("WIFIJOB1");