Android 12 (API level is 31) introduced foreground service start limit . Except for a small number of special scenes , if your app's targetSdkVersion is Android 12 or higher API level, the foreground service will no longer be able to be started when the app is running in the background. This means that if the current state of the application does not meet the conditions for starting the service in the background, the exception may be thrown when setForeground ).
Therefore, we have made some improvements in WorkManager 2.7 so that applications can easily schedule important tasks while complying with background restrictions. Through the urgent task , the application can easily run the time-consuming and high-priority task , such as sending a chat message or uploading a picture to a social network. It is recommended to use urgent tasks to start tasks that need to be executed immediately and can continue to be executed even if the user puts the application in the background.
If you need to set an urgent task, you can call the setExpedited() method through the Builder object of WorkRequest:
val request = OneTimeWorkRequestBuilder<HighPriorityWorker>()
.setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST)
.build()
WorkManager.getInstance(context).enqueue(request)
Tell the framework that this task is important and has a higher priority than other tasks by calling setExpedited(). OutOfQuotaPolicy parameter when calling the setExpedited() method. tasks are subject to the quota limit based on 16178d5d5bbf95 App Standby Buckets (App Standby Buckets) . When your app tries to execute urgent tasks when the quota is exceeded, WorkManager will act accordingly according to the OutOfQuotaPolicy parameter: Give up completely Urgent task request (DROP_WORK_REQUEST), or downgrade the urgent task to a normal task (RUN_AS_NON_EXPEDITED_WORK_REQUEST). The urgent task is important, but it does not mean that it can be executed all the time. You need to treat the quota as a time limit to execute the urgent task.
WorkManager 2.7 is backward compatible and can run on systems prior to Android 12. When calling setExpedited() on Android 11 or earlier versions, WorkManager will use foreground services instead of urgent tasks by default.
To understand the actual combat of the setExpedited() API in WorkManager, please refer to the official example and document .
You can view the detailed list of changes and optimizations in each version of WorkManager in the official release notes, as well as the release notes for WorkManager 2.6 and WorkManager 2.7
If you have any functional requirements or problems related to WorkManager, please submit issue in our public issue tracker.
Welcome to click here to submit feedback to us, or share your favorite content or problems found. Your feedback is very important to us, thank you for your support!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。