WorkManager, doWork() gets called twice with the same id unintentionally

Viewed 925

WorkManager does the doWork() twice. Even while using .enqueueUniquePeriodicWork() I get duplicates with the same id that runs in parallel.

My custom constraint that only allows work to be done while screen is off works but when conditions are met it goes of twice.

I've tried to cancel and prune all pre-existing work but doWork() still gets called twice.

button gets clicked ->

           Log.i("[Worker]","Start");
            // Change every 15 minutes.

            PeriodicWorkRequest.Builder builder = new PeriodicWorkRequest.Builder(Worker.class, 15, TimeUnit.MINUTES);
            builder.setConstraints(Constraints.NONE);
            builder.setBackoffCriteria(BackoffPolicy.LINEAR,30,TimeUnit.SECONDS);
            builder.addTag("loader");

            PeriodicWorkRequest request = builder.build();
            // cancel all work
            WorkManager.getInstance().cancelAllWork();
            // clear all finished or cancelled tasks from the WorkManager
            WorkManager.getInstance().pruneWork();
            // Start PeriodicWork
            WorkManager.getInstance().enqueueUniquePeriodicWork(request.getId().toString(),REPLACE,request);

// Worker.java

public Worker.Result doWork() {
    // Print workId
    // Is screen on
    PowerManager pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);

    boolean isScreenOn = pm.isInteractive();

    int r = getRunAttemptCount()+1;

    if (!isScreenOn) {
        Log.i("[Worker]", "workId: " + getId());
        // CODE
    } else if (isScreenOn) {
        Log.i("[Worker]","Fail: Retry "+r);
       return Result.retry();
    }
    return Result.success();
}

// Logs

Log.i:
Time: 16:23:00.634 [Worker]: Start <br>
Time: 16:23:00.963 [Worker]: Fail: Retry 1<br>
Time: 16:23:31.052 [Worker]: workId: 90369ace-2e0b-4398-8cf1-6e5c3cd306c5<br>
Time: 16:23:31.168 [Worker]: workId: 90369ace-2e0b-4398-8cf1-6e5c3cd306c5<br>


dependencies {
    def work_version = "2.0.1"<br>
    implementation "androidx.work:work-runtime:$work_version"<br>
}
1 Answers

These aren't running in parallel. Your work runs immediately on app start because it's being retried. In the meantime, you try to cancel it and run a new one immediately. You can see the timestamps are different.

Related