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>
This commit is contained in:
Isilsolme
2026-05-31 19:45:11 +08:00
co-authored by Claude Opus 4.8
parent c63cf8921d
commit 59468d1bc2
2 changed files with 6 additions and 2 deletions
@@ -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)
@@ -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,