How does setExpedited work and is it as good&reliable as a foreground service?

Conceptually Foreground Services & Expedited Work are not the same thing.

Only a OneTimeWorkRequest can be run expedited as these are time sensitive. Any Worker can request to be run in the foreground. That might succeed depending on the app’s foreground state.

A Worker can try to run its work in the foreground using setForeground[Async]() like this from WorkManager 2.7 onwards:

class DownloadWorker(context: Context, parameters: WorkerParameters) :
    CoroutineWorker(context, parameters) {

    override suspend fun getForegroundInfo(): ForegroundInfo {
        TODO()
    }

    override suspend fun doWork(): Result {
        return try {
            setForeground(getForegroundInfo())
            Result.success()
        } catch(e: ForegroundServiceStartNotAllowedException) {
            // TODO handle according to your use case or fail.
            Result.fail()
        }
    }
}


You can request a WorkRequest to be run ASAP by using setExpedited when building it.

val request = OneTimeWorkRequestBuilder<SendMessageWorker>()
    .setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST)
    .build()


WorkManager.getInstance(context)
    .enqueue(request)

On Android versions before 12 expedited jobs will be run as a foreground service, showing a notification. On Android 12+ the notification might not be shown.

Diagram of when to use Foreground Services & Expedited Jobs

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)