I am using a BroadcastReceiver
in my code. The code in the onReceive()
is not asynchronous but I am not sure it will always last less than 10 seconds, because, as specified here, an ANR will be raised.
I am looking to implement a simple WorkManager to make sure the instructions will be executed even when they require more than 10 seconds, but it is unclear to me how to use it in this context. I don't want the task to be scheduled, I'd like them to be executed as soon as a Broadcast is received (just like how it works in the onReceive()
).
Thank you in advance!
CodePudding user response:
You can't be sure. The idea of WorkManager is for the work to:
- finish for sure
- spare resources
There is nothing like:
- let's do it whenever we want.
If your use case somehow can raise a Service - this is how you can do it "right now". But as you might know - there are restrictions for starting a service from the background:
https://developer.android.com/about/versions/oreo/background#services
And the other option is to use expedited work. It raises the priority of the work and it is precisely for your case. It will "most likely" start the work now. But you can't be sure at all:
https://developer.android.com/topic/libraries/architecture/workmanager/how-to/define-work#expedited
WorkManager 2.7.0 introduced the concept of expedited work. This allows WorkManager to execute important work while giving the system better control over access to resources.
Expedited work is notable for the following characteristics:
- Importance: Expedited work suits tasks which are important to the user or are user-initiated.
- Speed: Expedited work best fits short tasks that start immediately and complete within a few minutes.
- Quotas: A system-level quota that limits foreground execution time determines whether an expedited job can start.
- Power Management: Power management restrictions, such as Battery Saver and Doze, are less likely to affect expedited work.
- Latency: The system immediately executes expedited work, provided that the system's current workload enables it to do so. This means they are latency sensitive and can't be scheduled for later execution.
CodePudding user response:
- You can use a WorkManager with an expedited flag set to true.
- You can run a foreground service with a notification in the tray.