Modern Apps git

← Modern-Apps.git

watch: schedule conduit sync triggers on connect, register, and a timer

Commit
8225851dbd798cd7931ce595f7aa801e342fd977
Author
Vayun Mathur <[email protected]>
When
2026-12-05 01:22 UTC (1 day ago)
Parents
8d79cb0
ConduitSyncScheduler (started by ConduitService) persists every
registered appId-to-package pair in ConduitSyncRegistry — an app
opts in simply by registering its conduit client — and fires the
ConduitSync.ACTION intent on RFCOMM link connect and on each new
registration. ConduitSyncWorker adds the 15-minute periodic
trigger via WorkManager (minimum period, no user setting). The
intent is package-addressed and requires the CONDUIT signature
permission; absent apps are tolerated.

Verified: :watch:lint, :watch:lintVitalRelease, and
:watch:testDevUnitTest pass.

Diff

watch/AGENTS.md
diff --git a/watch/AGENTS.md b/watch/AGENTS.mdindex 7608a36889..15c4f2cea7 100644--- a/watch/AGENTS.md+++ b/watch/AGENTS.md@@ -24,6 +24,14 @@ the peer. `platform/BootReceiver` restarts it on boot/replacement. The single status screen renders `ConduitRuntime.state` (link state, registered apps, per-app counters) and offers the Bluetooth permission grant.+**Scheduled push sync:** `service/ConduitSyncScheduler` (started by+`ConduitService`) maintains the persisted registry of sync-capable+apps (`ConduitSyncRegistry`: every appId that has registered with+the conduit, with its package — new apps opt in by registering) and+fires the `ConduitSync.ACTION` intent at each registered app on+three triggers: the RFCOMM link connecting, a phone app registering,+and `service/ConduitSyncWorker`'s 15-minute WorkManager period.+Absent apps are tolerated; the intent carries only the appId. **Entry points + reading order:** `Route` (`Status`) → `MainActivity.kt` → `Navigation.kt` → `ui/WatchStatusScreen.kt`; service side: `service/ConduitService.kt` → `:library:wearlink` conduit package.
watch/build.gradle.kts
diff --git a/watch/build.gradle.kts b/watch/build.gradle.ktsindex f225531a3b..2feed26a48 100644--- a/watch/build.gradle.kts+++ b/watch/build.gradle.kts@@ -18,4 +18,6 @@ dependencies {     // conduit protocol/router/host live in :library:wearlink.     implementation(project(":library:wearlink"))     implementation(libs.kotlinx.coroutines.android)+    // Periodic conduit sync trigger (ConduitSyncWorker, 15 min).+    implementation(libs.androidx.work.runtime.ktx) }
watch/src/main/java/com/vayunmathur/watch/service/ConduitService.kt
diff --git a/watch/src/main/java/com/vayunmathur/watch/service/ConduitService.kt b/watch/src/main/java/com/vayunmathur/watch/service/ConduitService.ktindex ab7c615b15..f102bf13c7 100644--- a/watch/src/main/java/com/vayunmathur/watch/service/ConduitService.kt+++ b/watch/src/main/java/com/vayunmathur/watch/service/ConduitService.kt@@ -11,6 +11,9 @@ import android.os.IBinder import androidx.core.app.NotificationCompat import androidx.core.content.ContextCompat import com.vayunmathur.library.wearlink.conduit.ConduitHost+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob  /**  * Foreground host for the one WearLink conduit on this device.@@ -25,10 +28,13 @@ import com.vayunmathur.library.wearlink.conduit.ConduitHost class ConduitService : Service() {     private lateinit var host: ConduitHost     private var foregroundStarted = false+    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+    private lateinit var syncScheduler: ConduitSyncScheduler      override fun onCreate() {         super.onCreate()         host = ConduitHost(applicationContext)+        syncScheduler = ConduitSyncScheduler(applicationContext, scope)         createChannel()     } @@ -40,6 +46,7 @@ class ConduitService : Service() {         startForegroundNow()         if (!foregroundStarted) return START_NOT_STICKY         host.start()+        syncScheduler.start()         return START_STICKY     } 
watch/src/main/java/com/vayunmathur/watch/service/ConduitSyncScheduler.kt
diff --git a/watch/src/main/java/com/vayunmathur/watch/service/ConduitSyncScheduler.kt b/watch/src/main/java/com/vayunmathur/watch/service/ConduitSyncScheduler.ktnew file mode 100644index 0000000000..1e14677c74--- /dev/null+++ b/watch/src/main/java/com/vayunmathur/watch/service/ConduitSyncScheduler.kt@@ -0,0 +1,119 @@+package com.vayunmathur.watch.service++import android.content.Context+import android.content.Intent+import com.vayunmathur.library.log.Log+import com.vayunmathur.library.wearlink.conduit.ConduitProtocol+import com.vayunmathur.library.wearlink.conduit.ConduitRuntime+import com.vayunmathur.library.wearlink.conduit.ConduitSync+import com.vayunmathur.library.wearlink.conduit.ConduitSyncDispatcher+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.flow.collectLatest+import kotlinx.coroutines.launch++/**+ * Persistent registry of sync-capable apps: every appId that has ever+ * registered with the conduit, with the package it registered from.+ * Fed from [ConduitRuntime] registrations (an app opts in simply by+ * registering its conduit client) and kept across process death so the+ * periodic trigger can still address apps that are not running.+ */+object ConduitSyncRegistry {+    private const val PREFS = "conduit_sync_registry"++    fun load(context: Context): Map<String, String> =+        context+            .getSharedPreferences(PREFS, Context.MODE_PRIVATE)+            .all+            .entries+            .mapNotNull { (key, value) -> (value as? String)?.let { key to it } }+            .toMap()++    /** Merge [packages] into the persisted registry; returns the full registry. */+    fun record(+        context: Context,+        packages: Map<String, String>,+    ): Map<String, String> {+        if (packages.isNotEmpty()) {+            val editor = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()+            for ((appId, pkg) in packages) editor.putString(appId, pkg)+            editor.apply()+        }+        return load(context)+    }+}++/**+ * The three scheduled triggers for the conduit push sync, run by the+ * phone Watch app:+ * (a) the RFCOMM link to the watch connects,+ * (b) periodically (WorkManager, see [ConduitSyncWorker]),+ * (c) a phone app registers with the conduit.+ * Each fires the [ConduitSync.ACTION] intent at every registered app;+ * absent apps are tolerated. Change-triggered pushes (an app's own+ * data changing, in either direction) ride the same conduit publish+ * paths and need no scheduler involvement.+ */+class ConduitSyncScheduler(+    private val context: Context,+    private val scope: CoroutineScope,+) {+    private val appContext = context.applicationContext++    private val dispatcher =+        ConduitSyncDispatcher { appId, packageName -> sendTrigger(appId, packageName) }++    private var started = false++    fun start() {+        if (started) return+        started = true+        ConduitSyncWorker.schedule(appContext)+        scope.launch {+            var previousApps = emptySet<String>()+            var wasConnected = false+            ConduitRuntime.state.collectLatest { snapshot ->+                val registry = ConduitSyncRegistry.record(appContext, snapshot.registeredPackages)+                val fresh = ConduitSync.newlyRegistered(previousApps, snapshot.registeredApps)+                previousApps = snapshot.registeredApps+                for (appId in fresh) {+                    val pkg = registry[appId] ?: ConduitSync.defaultPackage(appId)+                    dispatcher.dispatch(appId, pkg)+                }+                val connected = snapshot.linkState == ConduitProtocol.STATUS_CONNECTED+                if (connected && !wasConnected) dispatchAll()+                wasConnected = connected+            }+        }+    }++    /** Trigger every app in the persisted registry (the periodic worker's entry). */+    fun dispatchAll() {+        val delivered = dispatcher.dispatchAll(ConduitSyncRegistry.load(appContext))+        Log.status(TAG, "sync trigger delivered to $delivered")+    }++    private fun sendTrigger(+        appId: String,+        packageName: String,+    ): Boolean {+        val installed =+            runCatching {+                appContext.packageManager.getPackageInfo(packageName, 0)+                true+            }.getOrDefault(false)+        if (!installed) return false+        val intent =+            Intent(ConduitSync.ACTION).apply {+                setPackage(packageName)+                putExtra(ConduitSync.EXTRA_APP_ID, appId)+            }+        // Only receivers holding the signature permission may receive it.+        appContext.sendBroadcast(intent, ConduitSync.PERMISSION)+        return true+    }++    companion object {+        private const val TAG = "ConduitSyncScheduler"+    }+}
watch/src/main/java/com/vayunmathur/watch/service/ConduitSyncWorker.kt
diff --git a/watch/src/main/java/com/vayunmathur/watch/service/ConduitSyncWorker.kt b/watch/src/main/java/com/vayunmathur/watch/service/ConduitSyncWorker.ktnew file mode 100644index 0000000000..aa29e031c8--- /dev/null+++ b/watch/src/main/java/com/vayunmathur/watch/service/ConduitSyncWorker.kt@@ -0,0 +1,41 @@+package com.vayunmathur.watch.service++import android.content.Context+import androidx.work.CoroutineWorker+import androidx.work.ExistingPeriodicWorkPolicy+import androidx.work.PeriodicWorkRequestBuilder+import androidx.work.WorkManager+import androidx.work.WorkerParameters+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import java.util.concurrent.TimeUnit++/**+ * Periodic sync trigger (15 minutes, WorkManager's minimum period;+ * battery-friendly by construction, no user setting). Fires the+ * [com.vayunmathur.library.wearlink.conduit.ConduitSync.ACTION] intent+ * at every app in the persisted conduit registry.+ */+class ConduitSyncWorker(+    context: Context,+    params: WorkerParameters,+) : CoroutineWorker(context, params) {+    override suspend fun doWork(): Result {+        ConduitSyncScheduler(applicationContext, CoroutineScope(SupervisorJob() + Dispatchers.IO)).dispatchAll()+        return Result.success()+    }++    companion object {+        private const val UNIQUE_NAME = "conduit_sync_trigger"++        /** Enqueue the periodic trigger once (kept across updates). */+        fun schedule(context: Context) {+            val request =+                PeriodicWorkRequestBuilder<ConduitSyncWorker>(15, TimeUnit.MINUTES).build()+            WorkManager+                .getInstance(context.applicationContext)+                .enqueueUniquePeriodicWork(UNIQUE_NAME, ExistingPeriodicWorkPolicy.KEEP, request)+        }+    }+}