Short Story :
I have a ListenableWorker that performs tasks involving fetching data from a local database and performing checks with this data. However, I have noticed that the onStopped() method of the worker is sometimes called while my code is still executing. This raises concerns about potential problems during long-running tasks that may span 12-18 hours. I'm unsure how this could happen and if it might cause issues for keeping the worker alive.
Long Story :
In my application I need to run a task for user-defined duration at a user-selected start time.
For Example : A user can specify running this task fom 10:00 P.M. for Half an hour
or from 9 A.M. for 12 hours,
Both the start time and duration are selected by the user
To handle this, I store the start time and duration in a local Database using Room and utilize WorkManager/Alarms to initiate the work.
Previously, I used a Foreground Notification Service for long-running tasks, but due to restrictions introduced in Android 12, I'm migrating to WorkManager.
My current approach for managing a WorkManager's Listenable Worker and keeping it alive for the specified duration is as follows:
- My Worker is of type ListenableWorker which I am using with a ResolvableFuture<Result>, which is being returned from startWork() since it takes ListenableFuture<Result> as return type
- In startWork() I fetch data from Room Database, perform various checks and apply logic
- I also register a BroadcastReceiver to listen to specific user actions.
- And if everything is in order, I call setForegroundAsync() to keep the worker running and show a notification to the user using the same.
- If I need to stop the worker before completing the entire task, I use set(Result.failure()) on the ResolvableFuture<Result> returned from startWork().
- I use a Handler() with a delayed Runnable which is triggered after the user-specified duration and after the specified duration, I call set(Result.Success()) on the same ResolvableFuture<Result> to stop the worker.
Now I have two concerns:
1) I'm uncertain if this approach is suitable for my use case and if there are alternative options for handling this kind of long-running work from the background.
2) I'm facing an issue where the onStopped() callback of the ListenableWorker is invoked while my code is still executing.
I would appreciate any insights or suggestions on why this might occur and if there are improvements or alternative approaches I should consider.
Thank you in advance for any assistance or guidance you can provide.