My works scheduled in the WorkManager are not always being executing when the app in the background. This is how I schedule them:
Constraints myConstraints = new Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build();
OneTimeWorkRequest batchingWork = new OneTimeWorkRequest.Builder(BatchingJobWorker.class)
.setConstraints(myConstraints)
.setInitialDelay(minLatencyJobs, TimeUnit.MILLISECONDS)
.setBackoffCriteria(BackoffPolicy.LINEAR, 10 * 1000, TimeUnit.MILLISECONDS)
.addTag(BATCHING_JOB_WORK)
.build();
WorkManager.getInstance(context)
.enqueueUniqueWork(BATCHING_JOB_WORK, ExistingWorkPolicy.APPEND, batchingWork);
I read from this other thread that the problem could be that the Android operating system could be killing / force stopping the app so that the services, schedulers, alarms, broadcast receivers, etc., are no longer working.
However, in my case I'm scheduling the job from a background service and the delays I'm setting are small (1 min or less), so I know that the app is running at that moment. Also, I'm testing this with my testing devices, so I know no one is killing the app by swipping it from the recents menu. This is the exact procedure I'm following:
- An MQTT message is received in the background service
- I request a PARTIAL_WAKE_LOCK
- Some code is executed (I know this code is being called, so I suppose the MQTT and background service part is working fine).
- I schedule the work in the WorkManager.
As I said, in some cases the doWork() of the worker is not executed. These are some tests I did:
- When the work is scheduled in a running activity with a button click and the app is in foreground, it works as expected.
- Disabling the battery saver mode in some phones seems to help, but It doesn't fix the problem in 100% of the cases.
- Some smartphones or ROMs seem to have higher probability of executing the scheduled work.
- When the worker doesn't executes I don't see any exception in the log.
- The failure probability seems to increase with the amount of previous jobs executed in the background. In fact, when no more works are being executing, usually reinstalling the app fixes the problem.
- With the device connected to power seems to work better.
Could anyone with me a clue about what is happening here? Am I doing something wrong?
Thanking you in advance.