Skip to content

Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.

fix(settings): one read per save in settings listeners, not one per key

Durganshu7a7210e59d60
diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.kt
index 1c65187..198263b 100644
--- a/app/src/main/java/com/gotcha/MainActivity.kt
+++ b/app/src/main/java/com/gotcha/MainActivity.kt
@@ -192,13 +192,13 @@ class MainActivity : ComponentActivity() {
/**
* Repaints when the skin is written from outside the Appearance screen — the
* assistant's update_gotcha_settings (issue #99) — without a restart. Held in a
- * field: SharedPreferences keeps listeners weakly.
+ * field: SharedPreferences keeps listeners weakly. Coalesced, because every
+ * save notifies once per setting (see [com.gotcha.data.coalescedSettingsListener]).
*/
- private val appearanceListener =
- android.content.SharedPreferences.OnSharedPreferenceChangeListener { _, _ -> syncAppearance() }
+ private val appearanceListener = com.gotcha.data.coalescedSettingsListener { syncAppearance() }
private fun syncAppearance() {
- val latest = settingsRepository.load().appearance()
+ val latest = Appearance(skinId = settingsRepository.loadSkinId())
if (latest != appearance) {
appearance = latest
applyLaunchBackground()
diff --git a/app/src/main/java/com/gotcha/data/SettingsRepository.kt b/app/src/main/java/com/gotcha/data/SettingsRepository.kt
index 06c3627..215eeac 100644
--- a/app/src/main/java/com/gotcha/data/SettingsRepository.kt
+++ b/app/src/main/java/com/gotcha/data/SettingsRepository.kt
@@ -2,9 +2,12 @@ package com.gotcha.data
import android.content.Context
import android.content.SharedPreferences
+import android.os.Handler
+import android.os.Looper
import com.gotcha.BuildConfig
import com.gotcha.audio.AudioProvider
import com.gotcha.i18n.Language
+import java.util.concurrent.atomic.AtomicBoolean
/**
* When the wake-word listener is allowed to run, relative to the screen state.
@@ -495,6 +498,36 @@ internal const val SETTINGS_PREFS_FILE = "gotcha_settings"
fun settingsChangeNotifier(context: Context): SharedPreferences =
context.applicationContext.getSharedPreferences(SETTINGS_PREFS_FILE, Context.MODE_PRIVATE)
+/**
+ * A [settingsChangeNotifier] listener that runs [onChange] once per burst of
+ * writes, on [handler]'s thread, instead of once per key.
+ *
+ * [SettingsRepository.save] rewrites every key, and each value is re-encrypted
+ * under a fresh IV, so the framework sees every key as changed: one save is
+ * one notification per setting, delivered synchronously inside `apply()` on
+ * the saving thread. A listener that reads settings back on each of those
+ * multiplies the decrypts by the number of keys, which on a slow phone is
+ * seconds on the main thread — long enough for an ANR from tapping a skin.
+ *
+ * Posting means [onChange] runs after the burst, so it reads the finished
+ * write; the pending flag keeps the burst to a single post. Hold the returned
+ * listener in a field: the framework keeps listeners weakly.
+ */
+fun coalescedSettingsListener(
+ handler: Handler = Handler(Looper.getMainLooper()),
+ onChange: () -> Unit
+): SharedPreferences.OnSharedPreferenceChangeListener {
+ val pending = AtomicBoolean(false)
+ return SharedPreferences.OnSharedPreferenceChangeListener { _, _ ->
+ if (pending.compareAndSet(false, true)) {
+ handler.post {
+ pending.set(false)
+ onChange()
+ }
+ }
+ }
+}
+
internal const val SKIN_DEEP_SPACE_DARK = "deepspace"
internal const val SKIN_DEEP_SPACE_LIGHT = "deepspace_light"
internal const val SKIN_VELLUM = "vellum"
@@ -545,6 +578,12 @@ class SettingsRepository(context: Context) : SettingsStore {
private fun string(key: String, default: String = ""): String =
prefs.getString(key, default) ?: default
+ /**
+ * Just the skin, for the listeners that repaint on a change: one decrypt
+ * where [load] does one per setting.
+ */
+ fun loadSkinId(): String = resolvedSkinId()
+
/** Reads the stored skin, running the one-shot migration if it has not run. */
private fun resolvedSkinId(): String {
val stored = prefs.getString(KEY_SKIN_ID, null)
diff --git a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt b/app/src/main/java/com/gotcha/service/AssistiveBallService.kt
index ead116f..a3d048a 100644
--- a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt
+++ b/app/src/main/java/com/gotcha/service/AssistiveBallService.kt
@@ -23,6 +23,7 @@ import com.gotcha.audio.TtsEngine
import com.gotcha.data.ChatHistoryRepository
import com.gotcha.data.SettingsRepository
import com.gotcha.data.WakeWordListeningMode
+import com.gotcha.data.coalescedSettingsListener
import com.gotcha.data.settingsChangeNotifier
import com.gotcha.i18n.stringLookup
import com.gotcha.ui.AssistiveBallOverlay
@@ -84,11 +85,12 @@ class AssistiveBallService : Service() {
private lateinit var settingsPrefs: SharedPreferences
/** Reacts to wake-word settings edits while the ball is running. */
- private val wakeWordSettingsWatcher = SharedPreferences.OnSharedPreferenceChangeListener { _, _ ->
+ // Coalesced: every save notifies once per setting, and this reads them all.
+ private val wakeWordSettingsWatcher = coalescedSettingsListener {
val s = settingsRepository.load()
if (!s.wakeWordEnabled || !s.assistiveBallEnabled) {
wakeWordDetector.release()
- return@OnSharedPreferenceChangeListener
+ return@coalescedSettingsListener
}
// The key arrives encrypted; compare the value read back instead (see
// settingsChangeNotifier's note). Restarting with a new threshold or a
diff --git a/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt b/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt
index ef0a81d..0d38962 100644
--- a/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt
+++ b/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt
@@ -2,7 +2,6 @@ package com.gotcha.ui
import android.animation.ValueAnimator
import android.content.Context
-import android.content.SharedPreferences
import android.graphics.Color
import android.graphics.PixelFormat
import android.graphics.Typeface
@@ -24,6 +23,7 @@ import android.widget.TextView
import androidx.core.graphics.ColorUtils
import com.gotcha.R
import com.gotcha.data.SettingsRepository
+import com.gotcha.data.coalescedSettingsListener
import com.gotcha.data.settingsChangeNotifier
import com.gotcha.service.EntityType
import com.gotcha.service.ProactiveSessionItem
@@ -151,13 +151,11 @@ class AssistiveBallOverlay(context: Context) {
* list per instance and Appearance saves through an instance of its own.
*
* The key is ignored: it arrives encrypted, and `save` writes every setting
- * at once so almost anything fires this. Reading the skin back and
- * comparing is the only thing that works, and it is what makes the listener
- * cheap enough not to care how often it runs.
+ * at once so almost anything fires this — once per setting. Reading the
+ * skin back and comparing is the only thing that works, so the burst is
+ * coalesced into one read (see [coalescedSettingsListener]).
*/
- private val skinWatcher = SharedPreferences.OnSharedPreferenceChangeListener { _, _ ->
- mainHandler.post { restyleIfSkinChanged() }
- }
+ private val skinWatcher = coalescedSettingsListener(mainHandler) { restyleIfSkinChanged() }
/** Put the ball back on screen after the display changes shape. */
private fun handleScreenChanged(previous: Size, current: Size) {
@@ -187,7 +185,7 @@ class AssistiveBallOverlay(context: Context) {
}
private fun currentSkinId(): String =
- runCatching { settingsRepository.load().skinId }.getOrDefault(Skins.OVERLAY_FALLBACK_ID)
+ runCatching { settingsRepository.loadSkinId() }.getOrDefault(Skins.OVERLAY_FALLBACK_ID)
/** The active skin, translated for View code. */
private fun palette(): OverlaySkin = overlaySkin(appContext, currentSkinId())
diff --git a/app/src/test/java/com/gotcha/data/SettingsChangeNotifierTest.kt b/app/src/test/java/com/gotcha/data/SettingsChangeNotifierTest.kt
index 3387d94..6d832c2 100644
--- a/app/src/test/java/com/gotcha/data/SettingsChangeNotifierTest.kt
+++ b/app/src/test/java/com/gotcha/data/SettingsChangeNotifierTest.kt
@@ -2,12 +2,15 @@ package com.gotcha.data
import android.content.Context
import android.content.SharedPreferences
+import android.os.Looper
import androidx.test.core.app.ApplicationProvider
+import org.junit.Assert.assertEquals
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
+import org.robolectric.Shadows.shadowOf
/**
* The assistive ball is built once and then lives as long as the service, so it
@@ -72,4 +75,27 @@ class SettingsChangeNotifierTest {
// repainting a window that is no longer on screen.
assertTrue("unregister must actually detach", fired[0] == 0)
}
+
+ @Test
+ fun `a coalesced listener runs once for a save that touches every key`() {
+ val fired = intArrayOf(0)
+ val watcher = coalescedSettingsListener { fired[0]++ }
+ listener = watcher
+ val prefs = settingsChangeNotifier(context)
+ prefs.registerOnSharedPreferenceChangeListener(watcher)
+
+ // What SettingsRepository.save looks like from here: every key in one
+ // apply, each with a new value (re-encryption gives every one a new IV).
+ prefs.edit().apply { repeat(58) { putString("burst_key_$it", "v$it") } }.apply()
+ shadowOf(Looper.getMainLooper()).idle()
+
+ // Per key, MainActivity re-read the settings 58 times inside one tap
+ // and the skin picker ANR'd on a slow phone.
+ assertEquals("one save must be one callback", 1, fired[0])
+
+ prefs.edit().putString("burst_key_0", "again").apply()
+ shadowOf(Looper.getMainLooper()).idle()
+ assertEquals("a later save must still be heard", 2, fired[0])
+ prefs.unregisterOnSharedPreferenceChangeListener(watcher)
+ }
}