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>
This commit is contained in:
Ahmad Ansori Palembani 2024-08-06 07:08:03 +07:00
parent 3168f87012
commit 97bd9c4bc8
Signed by: null2264
GPG key ID: BA64F8B60AF3EFB6

View file

@ -41,6 +41,7 @@ import eu.kanade.tachiyomi.data.preference.PreferencesHelper
import eu.kanade.tachiyomi.extension.util.ExtensionLoader import eu.kanade.tachiyomi.extension.util.ExtensionLoader
import eu.kanade.tachiyomi.ui.main.MainActivity import eu.kanade.tachiyomi.ui.main.MainActivity
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.Injekt
@ -406,6 +407,7 @@ fun setLocaleByAppCompat() {
suspend fun CoroutineWorker.tryToSetForeground() { suspend fun CoroutineWorker.tryToSetForeground() {
try { try {
setForeground(getForegroundInfo()) setForeground(getForegroundInfo())
delay(500)
} catch (e: IllegalStateException) { } catch (e: IllegalStateException) {
Logger.e(e) { "Not allowed to set foreground job" } Logger.e(e) { "Not allowed to set foreground job" }
} }