ソースを参照

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 <noreply@anthropic.com>
Isilsolme 5 ヶ月 前
親
コミット
59468d1bc2

+ 3 - 2
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 <T> 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)

+ 3 - 0
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<String>? = null,