wearlink: make open-on-phone survive stopped and background apps
- Commit
65ed43e871a953145314c9aeec6e29e032a9c3cb- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-06 15:51 UTC (2 hours ago)
- Parents
e0bb2e6
The watch open-on-phone wake failed on device for two independent reasons confirmed by the owner's calendar log (BAL_BLOCK on a plain receiver startActivity, Android 14+ with targetSdk 37) and by audit: the package-addressed wake broadcast carried no FLAG_INCLUDE_STOPPED_PACKAGES, so a never-launched or force-stopped app silently never received it; and ConduitRouter only recognised the suffix path, so camera's OPEN_ON_PHONE op was queued stale for an unregistered app instead of being dropped like other opens. OpenOnPhoneLauncher now launches through a self-sent PendingIntent whose ActivityOptions set MODE_BACKGROUND_ACTIVITY_START_ALLOWED as both creator and sender mode (the documented BAL grant), with the plain start as fallback, and suppresses duplicate launches for the same activity+entity inside two seconds (the owner's log shows the tap firing twice). ConduitHost adds the stopped-packages flag via OpenOnPhoneContract.broadcastFlags. Tests pin every open app's send path, appId and derived package, the broadcast flag, the dedupe window, the camera-op no-queue rule, and (in OpenOnPhoneManifestContractTest) every app's manifest receiver, CONDUIT permission, applicationId and receiver/MainActivity sources. Verified: :library:wearlink lint, lintVitalRelease and testDevUnitTest pass.
Diff
library/wearlink/AGENTS.md
diff --git a/library/wearlink/AGENTS.md b/library/wearlink/AGENTS.mdindex 27f3b3f3ce..ef851bc1d6 100644--- a/library/wearlink/AGENTS.md+++ b/library/wearlink/AGENTS.md@@ -62,10 +62,14 @@ app is absent), `OpenOnPhoneContract`/`OpenOnPhoneLauncher` (the watch open-on-phone wake: a `/<appId>/open-on-phone` message, or camera's `OPEN_ON_PHONE` op, for an app with no live registration is turned by `ConduitHost` into a package-addressed, signature-permission-broadcast that the app's manifest receiver answers by launching its-main activity as a new task; a registered app handles the message in-its sync listener and is not broadcast to, and unregistered open-requests are never queued for stale replay), and+broadcast carrying `FLAG_INCLUDE_STOPPED_PACKAGES` that the app's+manifest receiver (all fourteen open apps, email and securemail+included) answers by launching its main activity as a new task through+a background-start-allowed `PendingIntent` on Android 14+; a+registered app handles the message in its sync listener and is not+broadcast to, and unregistered open requests — the camera op included+— are never queued for stale replay; `OpenOnPhoneManifestContractTest`+pins every app's receiver, permission, package and send path), and `ConduitHost`/`ConduitRuntime` used by the two Watch apps' `ConduitService`s. Merged phone/watch pairs ship as single APKs whose phone and watch experiences pick their side at
library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitHost.kt
diff --git a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitHost.kt b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitHost.ktindex 5ac4278a9a..f53b711bd6 100644--- a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitHost.kt+++ b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitHost.kt@@ -303,6 +303,7 @@ class ConduitHost( val intent = Intent(OpenOnPhoneContract.ACTION).apply { setPackage(targetPackage)+ addFlags(OpenOnPhoneContract.broadcastFlags()) putExtra(OpenOnPhoneContract.EXTRA_APP_ID, appId) putExtra(OpenOnPhoneContract.EXTRA_ENTITY_ID, OpenOnPhoneContract.entityIdFor(path, body)) }
library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitRouter.kt
diff --git a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitRouter.kt b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitRouter.ktindex b01c67d8cb..8d91d19ddf 100644--- a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitRouter.kt+++ b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitRouter.kt@@ -233,7 +233,7 @@ class ConduitRouter( val client = clients[appId] if (client != null) { client.deliverMessage(path, body)- } else if (OpenOnPhoneContract.isOpenOnPhonePath(path)) {+ } else if (OpenOnPhoneContract.isOpenRequest(path, body)) { // An open-on-phone request is a momentary ask, not sync data: // the conduit host wakes the target app with a manifest // broadcast instead (see OpenOnPhoneContract). Queueing it here
library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/OpenOnPhone.kt
diff --git a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/OpenOnPhone.kt b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/OpenOnPhone.ktindex 74396e7439..e3c51802a5 100644--- a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/OpenOnPhone.kt+++ b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/OpenOnPhone.kt@@ -1,7 +1,10 @@ package com.vayunmathur.library.wearlink.conduit +import android.app.ActivityOptions+import android.app.PendingIntent import android.content.Context import android.content.Intent+import android.os.Build import com.vayunmathur.library.wearlink.WEAR_OPEN_ON_PHONE_PATH_SUFFIX import com.vayunmathur.library.wearlink.camera.WearCameraProtocol import com.vayunmathur.library.wearlink.camera.WearOpKind@@ -35,6 +38,34 @@ object OpenOnPhoneContract { /** Signature permission guarding every open-on-phone receiver. */ const val PERMISSION = ConduitProtocol.PERMISSION + /**+ * Flags for the wake broadcast: without+ * `FLAG_INCLUDE_STOPPED_PACKAGES` the platform silently drops a+ * package-addressed broadcast to an app that has never been launched+ * since install (or was force-stopped) — exactly the state an+ * open-on-phone tap is meant to recover from.+ */+ fun broadcastFlags(): Int = Intent.FLAG_INCLUDE_STOPPED_PACKAGES++ /** Every conduit appId whose watch experience sends an open request. */+ val OPEN_APP_IDS: List<String> =+ listOf(+ "notes",+ "clock",+ "calendar",+ "weather",+ "music",+ "contacts",+ "findfamily",+ "todo",+ "communicate",+ "launcher",+ "appstore",+ "camera",+ "email",+ "securemail",+ )+ /** True for the `/<appId>/open-on-phone` conduit message path. */ fun isOpenOnPhonePath(path: String): Boolean = path.endsWith(WEAR_OPEN_ON_PHONE_PATH_SUFFIX) @@ -119,11 +150,77 @@ object OpenOnPhoneLauncher { } } - /** Launch [activityClass] as a new task; false when the platform refuses. */+ /**+ * Launch [activityClass] as a new task; false when the platform refuses.+ *+ * On Android 14+ (the repo targets SDK 37) a plain `startActivity`+ * from a manifest broadcast receiver with no foreground/BAL privilege+ * can be blocked as a background activity start. The durable path is+ * a self-sent [PendingIntent] whose options explicitly allow the+ * background start (`MODE_BACKGROUND_ACTIVITY_START_ALLOWED`,+ * set both as creator and as sender mode — this self-PendingIntent+ * pattern is the documented way for a receiver/notification-style+ * caller to earn the BAL grant on Android 14+, confirmed on-device+ * 2026-12-06 where a plain receiver `startActivity` was logged+ * `BAL_BLOCK`); the direct start remains as a fallback if the+ * pending-intent send itself fails. Duplicate taps/retransmits for+ * the same activity+entity inside [DEDUPE_WINDOW_MS] are suppressed.+ */ fun launch( context: Context, activityClass: Class<*>, entityId: String,- ): Boolean =- runCatching { context.startActivity(buildIntent(context, activityClass, entityId)) }.isSuccess+ ): Boolean {+ if (!claimLaunch(activityClass.name, entityId, android.os.SystemClock.elapsedRealtime())) {+ return true+ }+ val intent = buildIntent(context, activityClass, entityId)+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {+ val sent =+ runCatching {+ val options =+ ActivityOptions.makeBasic()+ .setPendingIntentCreatorBackgroundActivityStartMode(+ ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED,+ )+ .setPendingIntentBackgroundActivityStartMode(+ ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED,+ )+ val pending =+ PendingIntent.getActivity(+ context,+ entityId.hashCode(),+ intent,+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,+ options.toBundle(),+ )+ pending.send(options.toBundle())+ }.isSuccess+ if (sent) return true+ }+ val direct = runCatching { context.startActivity(intent) }+ return direct.isSuccess+ }++ /** Window in which a repeat launch for the same target is a duplicate. */+ const val DEDUPE_WINDOW_MS: Long = 2_000L++ private var lastLaunchKey: String? = null+ private var lastLaunchMillis: Long = 0L++ /** True (and recorded) when this launch may proceed; false for a duplicate. */+ @Synchronized+ fun claimLaunch(+ activityClassName: String,+ entityId: String,+ nowMillis: Long,+ ): Boolean {+ val key = "$activityClassName#$entityId"+ val duplicate =+ key == lastLaunchKey && nowMillis - lastLaunchMillis in 0..<DEDUPE_WINDOW_MS+ if (duplicate) return false+ lastLaunchKey = key+ lastLaunchMillis = nowMillis+ return true+ } }
library/wearlink/src/test/java/com/vayunmathur/library/wearlink/conduit/ConduitRouterTest.kt
diff --git a/library/wearlink/src/test/java/com/vayunmathur/library/wearlink/conduit/ConduitRouterTest.kt b/library/wearlink/src/test/java/com/vayunmathur/library/wearlink/conduit/ConduitRouterTest.ktindex 7b4b9785a3..b95287ebb1 100644--- a/library/wearlink/src/test/java/com/vayunmathur/library/wearlink/conduit/ConduitRouterTest.kt+++ b/library/wearlink/src/test/java/com/vayunmathur/library/wearlink/conduit/ConduitRouterTest.kt@@ -145,6 +145,21 @@ class ConduitRouterTest { assertEquals(listOf("/todo/op"), todo.messages.map { it.first }) } + @Test+ fun `camera open op is never queued stale`() {+ val router = ConduitRouter(upstream = FakeUpstream())+ val openOp =+ com.vayunmathur.library.wearlink.camera+ .encodeWearCameraOp(+ com.vayunmathur.library.wearlink.camera+ .WearCameraOp(com.vayunmathur.library.wearlink.camera.WearOpKind.OPEN_ON_PHONE),+ )+ router.onPeerMessage(com.vayunmathur.library.wearlink.camera.WearCameraProtocol.OP_PATH, openOp)+ val late = FakeDownstream()+ router.register("camera", late)+ assertEquals(emptyList(), late.messages.map { it.first })+ }+ @Test fun `queued messages are bounded with oldest dropped`() { val router = ConduitRouter(maxQueuedPerApp = 2, upstream = FakeUpstream())
library/wearlink/src/test/java/com/vayunmathur/library/wearlink/conduit/OpenOnPhoneManifestContractTest.kt
diff --git a/library/wearlink/src/test/java/com/vayunmathur/library/wearlink/conduit/OpenOnPhoneManifestContractTest.kt b/library/wearlink/src/test/java/com/vayunmathur/library/wearlink/conduit/OpenOnPhoneManifestContractTest.ktnew file mode 100644index 0000000000..d381d0dbfc--- /dev/null+++ b/library/wearlink/src/test/java/com/vayunmathur/library/wearlink/conduit/OpenOnPhoneManifestContractTest.kt@@ -0,0 +1,97 @@+package com.vayunmathur.library.wearlink.conduit++import java.io.File+import kotlin.test.Test+import kotlin.test.assertTrue+import kotlin.test.fail++/**+ * Pins the per-app manifest contract the open-on-phone wake depends on:+ * for every app in [OpenOnPhoneContract.OPEN_APP_IDS] the phone manifest+ * must declare an exported `OpenOnPhoneReceiver` guarded by the CONDUIT+ * signature permission and answering [OpenOnPhoneContract.ACTION], the+ * module's `applicationId` must be the `com.vayunmathur.<appId>` package+ * the conduit host derives when no registration is known, a+ * `MainActivity` and an `OpenOnPhoneReceiver` source must exist, and the+ * watch send site must use the exact `/<appId>/open-on-phone` path (or,+ * for camera, the `OPEN_ON_PHONE` op). Reads the repo tree relative to+ * this module; fails loudly when an app drifts.+ */+class OpenOnPhoneManifestContractTest {+ private fun repoRoot(): File {+ var dir = File(System.getProperty("user.dir")).absoluteFile+ while (true) {+ if (File(dir, "settings.gradle.kts").isFile) return dir+ dir = dir.parentFile ?: fail("repo root not found from ${System.getProperty("user.dir")}")+ }+ }++ @Test+ fun `every open app declares the receiver, package and send path`() {+ val root = repoRoot()+ for (appId in OpenOnPhoneContract.OPEN_APP_IDS) {+ val module = File(root, appId)+ val manifest = File(module, "src/main/AndroidManifest.xml").readText()+ assertTrue(+ manifest.contains("android:name=\".sync.OpenOnPhoneReceiver\""),+ "$appId: OpenOnPhoneReceiver not declared",+ )+ assertTrue(+ manifest.contains("com.vayunmathur.watch.action.OPEN_ON_PHONE"),+ "$appId: OPEN_ON_PHONE action missing",+ )+ // The receiver block must be exported under the CONDUIT permission.+ val receiverBlock =+ manifest+ .split("<receiver")+ .firstOrNull { it.contains("OpenOnPhoneReceiver") }+ ?: fail("$appId: receiver block missing")+ assertTrue(receiverBlock.contains("android:exported=\"true\""), "$appId: receiver not exported")+ assertTrue(+ receiverBlock.contains("android:permission=\"com.vayunmathur.watch.permissions.CONDUIT\""),+ "$appId: receiver not guarded by CONDUIT permission",+ )+ val gradle = File(module, "build.gradle.kts").readText()+ assertTrue(+ gradle.contains("applicationId = \"com.vayunmathur.$appId\""),+ "$appId: applicationId is not com.vayunmathur.$appId",+ )+ assertTrue(+ gradle.contains("wearlink"),+ "$appId: no wearlink dependency (CONDUIT uses-permission is merged from it)",+ )+ // Sources: receiver + a MainActivity for it to launch exist.+ val sources = module.walkTopDown().filter { it.isFile && it.extension == "kt" }.toList()+ assertTrue(sources.any { it.name == "OpenOnPhoneReceiver.kt" }, "$appId: receiver source missing")+ assertTrue(sources.any { it.name == "MainActivity.kt" }, "$appId: MainActivity missing")+ // Watch send site uses the exact contract path (camera: the op).+ val sendSites =+ sources.filter { candidate ->+ val text = candidate.readText()+ text.contains("open-on-phone") || text.contains("OPEN_ON_PHONE")+ }+ if (appId == "camera") {+ assertTrue(+ sendSites.any { it.readText().contains("WearOpKind.OPEN_ON_PHONE") },+ "camera: OPEN_ON_PHONE op send site missing",+ )+ } else {+ assertTrue(+ sendSites.any { it.readText().contains("\"/$appId/open-on-phone\"") },+ "$appId: no watch send site for /$appId/open-on-phone",+ )+ }+ }+ // The shared library manifest is what merges the CONDUIT+ // uses-permission (the sendBroadcast receiver permission) into+ // every consuming app; without it no receiver would be eligible.+ val wearlinkManifest =+ File(root, "library/wearlink/src/main/AndroidManifest.xml").readText()+ assertTrue(+ wearlinkManifest.contains(+ "<uses-permission android:name=\"com.vayunmathur.watch.permissions.CONDUIT\" />",+ ),+ "wearlink library manifest must declare the CONDUIT uses-permission",+ )+ }+}
library/wearlink/src/test/java/com/vayunmathur/library/wearlink/conduit/OpenOnPhoneTest.kt
diff --git a/library/wearlink/src/test/java/com/vayunmathur/library/wearlink/conduit/OpenOnPhoneTest.kt b/library/wearlink/src/test/java/com/vayunmathur/library/wearlink/conduit/OpenOnPhoneTest.ktindex 4db906162b..3dfdb6e3ea 100644--- a/library/wearlink/src/test/java/com/vayunmathur/library/wearlink/conduit/OpenOnPhoneTest.kt+++ b/library/wearlink/src/test/java/com/vayunmathur/library/wearlink/conduit/OpenOnPhoneTest.kt@@ -50,6 +50,40 @@ class OpenOnPhoneTest { assertFalse(OpenOnPhoneContract.shouldHandle(null, "notes", "notes")) } + @Test+ fun `every watch send site path is an open request for its own app`() {+ // Literal paths copied from each app's watch send site+ // (/<appId>/open-on-phone via WearLinkBridge.sendMessage).+ for (appId in OpenOnPhoneContract.OPEN_APP_IDS) {+ val path = "/$appId/open-on-phone"+ assertTrue(OpenOnPhoneContract.isOpenRequest(path, ByteArray(0)), path)+ assertEquals(appId, OpenOnPhoneContract.appIdForPath(path), path)+ assertEquals(+ "com.vayunmathur.$appId",+ OpenOnPhoneContract.targetPackage(appId, emptyMap()),+ path,+ )+ }+ // Camera is the one exception: an OPEN_ON_PHONE op on /camera/op.+ assertEquals("camera", OpenOnPhoneContract.appIdForPath(WearCameraProtocol.OP_PATH))+ }++ @Test+ fun `wake broadcast includes stopped packages`() {+ assertTrue(+ OpenOnPhoneContract.broadcastFlags() and Intent.FLAG_INCLUDE_STOPPED_PACKAGES != 0,+ )+ }++ @Test+ fun `duplicate launches inside the window are suppressed`() {+ val activity = "com.vayunmathur.calendar.MainActivity"+ assertTrue(OpenOnPhoneLauncher.claimLaunch(activity, "evt-1", 10_000L))+ assertFalse(OpenOnPhoneLauncher.claimLaunch(activity, "evt-1", 11_000L))+ assertTrue(OpenOnPhoneLauncher.claimLaunch(activity, "evt-2", 11_500L))+ assertTrue(OpenOnPhoneLauncher.claimLaunch(activity, "evt-2", 14_000L))+ }+ @Test fun `launch spec carries new task, the component and the entity extra`() { val spec = OpenOnPhoneContract.launchSpec("com.vayunmathur.notes.MainActivity", "note-3")