Using WorkManager on Android 12

Caren Chang
Android Developers
Published in
2 min readSep 16, 2021

--

Android 12 (API level 31) introduces foreground service launch restrictions. With these restrictions, apps targeting Android 12 or higher can no longer start foreground services while running in the background, except for a few special cases. This means that calling setForeground may cause an exception if your app is not currently in a state that is exempt from background start restrictions.

Thus, in WorkManager 2.7, we’ve made it easy to schedule important work while adhering to background restrictions. With expedited jobs, apps can now easily execute short and high-priority tasks, such as sending a chat message or uploading a picture to a social network. Expedited jobs are the recommended way to start tasks that should run immediately and continue even if the user puts the app in the background.

To schedule work as expedited, use the setExpedited() method in the work request builder:

val request = OneTimeWorkRequestBuilder<HighPriorityWorker>()       
.setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST)
.build()
WorkManager.getInstance(context).enqueue(request)

Calling setExpedited() tells the framework that this work is important and should have priority over other scheduled work. Notice that we also passed an OutOfQuotaPolicy parameter into setExpedited(). Expedited jobs are subject to quotas based on App Standby Buckets, so the OutOfQuotaPolicy parameter tells WorkManager what to do if your app tries to run an expedited job while out of quota: either drop the expedited work request entirely (DROP_WORK_REQUEST), or fall back to having the job treated as a regular work request (RUN_AS_NON_EXPEDITED_WORK_REQUEST).

Think of quotas as time limits for executing your expedited job. Just because it is important, doesn’t mean that it can run forever.

WorkManager 2.7 is backwards compatible and will run on versions of Android older than 12. When calling setExpedited() on a device running Android 11 or older, WorkManager will default to using foreground services instead of expedited jobs.

To see WorkManager’s setExpedited() API in action, check out our official WorkManager Sample and documentation on expedited jobs.

You can also see a detailed list of changes and improvements made in each WorkManager release in the official release notes, along with specific release notes for Workmanager 2.6 and WorkManager 2.7.

Lastly, if you have any feature requests or issues related to WorkManager, feel free to file an issue in our public tracker.

--

--