blob: 66fe9ee2f000c664bc158a13de4686b7162801a8 [file] [log] [blame]
Sergey Vasilinetccb7647e2024-01-26 23:57:20 +00001/*
2 * Copyright 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package androidx.work.impl.utils
17
18import android.content.Context
19import android.os.Build
Sergey Vasilinetc85561342024-02-13 10:51:51 +000020import androidx.concurrent.futures.await
Sergey Vasilinetccb7647e2024-01-26 23:57:20 +000021import androidx.work.ForegroundUpdater
22import androidx.work.ListenableWorker
23import androidx.work.Logger
Sergey Vasilinetccb7647e2024-01-26 23:57:20 +000024import androidx.work.impl.model.WorkSpec
25import androidx.work.impl.utils.taskexecutor.TaskExecutor
26import androidx.work.logd
27import kotlinx.coroutines.asCoroutineDispatcher
28import kotlinx.coroutines.withContext
29
30suspend fun workForeground(
31 context: Context,
32 spec: WorkSpec,
33 worker: ListenableWorker,
34 foregroundUpdater: ForegroundUpdater,
35 taskExecutor: TaskExecutor
36) {
37 if (!spec.expedited || Build.VERSION.SDK_INT >= 31) return
38
39 val dispatcher = taskExecutor.mainThreadExecutor.asCoroutineDispatcher()
40 withContext(dispatcher) {
41 val foregroundInfo = worker.getForegroundInfoAsync().await()
42 if (foregroundInfo == null) {
43 val message =
44 "Worker was marked important (${spec.workerClassName}) " +
45 "but did not provide ForegroundInfo"
46 throw IllegalStateException(message)
47 }
48 logd(TAG) { "Updating notification for ${spec.workerClassName}" }
49 foregroundUpdater.setForegroundAsync(context, worker.id, foregroundInfo).await()
50 }
51}
52
53private val TAG = Logger.tagWithPrefix("WorkForegroundRunnable")