From 97bd9c4bc8ade8e3b795c5fbca0617ade347d03f Mon Sep 17 00:00:00 2001 From: Ahmad Ansori Palembani Date: Tue, 6 Aug 2024 07:08:03 +0700 Subject: [PATCH] fix(worker): Add delay to `tryToSetForeground` function > The system will crash the app if the worker that calls setForeground() finished > before the service runner be able to call Service.startForeground(). This edge > case is not handled by WorkManager and there is no way to check if the required > calls are done. The delay duration is a magic number where we assume by then the transition to foreground service is done. Seems to be an issue introduced in Android 8, and Google refuses to fix it, as usual. REF: https://developer.android.com/about/versions/oreo/background.html#services (Last paragraph of the section) REF: https://issuetracker.google.com/issues/76112072#comment36 (Status is set to Won't Fix) Co-authored-by: Ivan Iskandar <12537387+ivaniskandar@users.noreply.github.com> --- .../java/eu/kanade/tachiyomi/util/system/ContextExtensions.kt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/app/src/main/java/eu/kanade/tachiyomi/util/system/ContextExtensions.kt b/app/src/main/java/eu/kanade/tachiyomi/util/system/ContextExtensions.kt index 73923e92db..5e7e0d7dc6 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/util/system/ContextExtensions.kt +++ b/app/src/main/java/eu/kanade/tachiyomi/util/system/ContextExtensions.kt @@ -41,6 +41,7 @@ import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.extension.util.ExtensionLoader import eu.kanade.tachiyomi.ui.main.MainActivity import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.delay import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.withContext import uy.kohesive.injekt.Injekt @@ -406,6 +407,7 @@ fun setLocaleByAppCompat() { suspend fun CoroutineWorker.tryToSetForeground() { try { setForeground(getForegroundInfo()) + delay(500) } catch (e: IllegalStateException) { Logger.e(e) { "Not allowed to set foreground job" } }