From 59468d1bc2cf4d8c3e2911c0d204f39a6ead7bcf Mon Sep 17 00:00:00 2001 From: Isilsolme Date: Sun, 31 May 2026 19:45:11 +0800 Subject: [PATCH] Fix language preference not persisting after app restart Use commit() instead of apply() for String preference writes to ensure the value is written to disk synchronously before the process is killed during restart(). Root cause: SharedPreferences.apply() writes to memory immediately but commits to disk asynchronously. When context.restart() calls Process.killProcess()+exitProcess(0) immediately after writing the language preference, the async disk write may not complete, causing the new process to read the old value. Closes #862 Co-Authored-By: Claude Opus 4.8 --- app/src/main/java/io/legado/app/ui/config/PrefDelegate.kt | 5 +++-- app/src/main/java/io/legado/app/utils/ContextExtensions.kt | 3 +++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/io/legado/app/ui/config/PrefDelegate.kt b/app/src/main/java/io/legado/app/ui/config/PrefDelegate.kt index 495fc67d5..9dad8c6f0 100644 --- a/app/src/main/java/io/legado/app/ui/config/PrefDelegate.kt +++ b/app/src/main/java/io/legado/app/ui/config/PrefDelegate.kt @@ -12,11 +12,12 @@ import io.legado.app.utils.getPrefFloat import io.legado.app.utils.getPrefInt import io.legado.app.utils.getPrefLong import io.legado.app.utils.getPrefString +import io.legado.app.utils.putPrefString import io.legado.app.utils.putPrefBoolean import io.legado.app.utils.putPrefFloat import io.legado.app.utils.putPrefInt import io.legado.app.utils.putPrefLong -import io.legado.app.utils.putPrefString +import io.legado.app.utils.putPrefStringSync import splitties.init.appCtx import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty @@ -84,7 +85,7 @@ fun prefDelegate( override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) { if (_value.value != value) { when (value) { - is String? -> appCtx.putPrefString(key, value) + is String? -> appCtx.putPrefStringSync(key, value) is Int -> appCtx.putPrefInt(key, value) is Boolean -> appCtx.putPrefBoolean(key, value) is Long -> appCtx.putPrefLong(key, value) diff --git a/app/src/main/java/io/legado/app/utils/ContextExtensions.kt b/app/src/main/java/io/legado/app/utils/ContextExtensions.kt index 41b26c2bf..d7ddc57c1 100644 --- a/app/src/main/java/io/legado/app/utils/ContextExtensions.kt +++ b/app/src/main/java/io/legado/app/utils/ContextExtensions.kt @@ -223,6 +223,9 @@ fun Context.getPrefString(key: String, defValue: String? = null) = fun Context.putPrefString(key: String, value: String?) = defaultSharedPreferences.edit { putString(key, value) } +fun Context.putPrefStringSync(key: String, value: String?) = + defaultSharedPreferences.edit(commit = true) { putString(key, value) } + fun Context.getPrefStringSet( key: String, defValue: MutableSet? = null,