I have an android app that needs to perform some long running image processing in the background (processing many chunks of it)
- I used a WorkManager to perform the task
- I use a user notification to inform of the progress
Versions
- API Level 28
- Phone runnning Oreo
androidx.work:work-runtime:2.1.0
The WorkManager is setup as follows (simplified code)
@NonNull
@Override
public Result doWork() {
// 1 Create a NotificationChannel with unique ID
// 2 read params from getInputData
// 3 create as many instances of a class
// that extends Callable<String> as there are small subtasks
// 4 add all these tasks to a ThreadPoolExecutor and call
// invokeAll() which blocks the main Worker thread as required
// by the WorkManager API
// 5 Everytime a subtask finishes, update the notification progress
}
@Override
public void onStopped(){
// Call .shutDown() on the ThreadPoolExecutor
}
The work itself is submitted with the following parameters
WorkManager mWorkManager = WorkManager.getInstance(context);
Data input = new Data.Builder()
.putString(PARAM_IN_DTO, dto.toString())
.build();
OneTimeWorkRequest mRequest = new OneTimeWorkRequest
.Builder(ExtractorWorker.class)
.setInputData(input)
.addTag(dto.mapName)
.build();
mWorkManager.enqueueUniqueWork(
WORK_NAME,
ExistingWorkPolicy.KEEP,
mRequest);
As WORK_NAME
is unique with the code above I would expect there to never be two tasks running at the same time (note I tried with ExistingWorkPolicy.REPLACE
- same issue)
The job starts correctly and the progress in the notification starts updating. After a while, it seems that the task is started again with the previous one still running. I see this from the unique notification toggleing between two states (the notification age between now
and the previous age, and the progress between 0% and the previous progress). There is clearly two tasks now that update the same notification. I confirmed this by setting a random notification ID instead of a unique one, and two notifications appeared, each living their own life.
I wonder
- Why would WorkManager submit this task again while the previous one is still running and I haven't requested anything from the app
- How can there be two jobs running at the same time if I submit only one with
enqueueUniqueWork