I'm using WorkManager to start a background service once the user moves the App to the background or closes the App (OneTimeRequest), here's my code:
public static void scheduleSessionAnalyticsWorker(Data inputData) {
Constraints shouldBeConnected = new Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build();
OneTimeWorkRequest request = new OneTimeWorkRequest.Builder(AnalyticsWorker.class)
.addTag("WORKER_TAG")
.setInputData(inputData)
.setConstraints(shouldBeConnected)
.setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 5, TimeUnit.SECONDS)
.build();
WorkManager.getInstance(CoreApp.get().getBaseContext())
.enqueueUniqueWork("WORKER_TAG", ExistingWorkPolicy.KEEP, request);
}
In the case of moving the App to the background, I can clearly see that the WorkManager has started, and the startWork()/ doWork() method is called.
But in the case when closing the App, the work is enqueued successfully but it never executes!
I'm sure about the fact that the Work is enqueued because once I re-open the App I call:
List<WorkInfo> workInfos = WorkManager.getInstance(context).getWorkInfosByTag("WORKER_TAG").get();
And I can see that the list items have a State.ENQUEUED status.
So, Is there is a way to run all pending requests once the user re-enters the App?
And why WorkManager don't start immediately if it was scheduled before closing the App (even though it meets all the constraints), shouldn't background services be independent from the App context?