feat(watch): Wear OS companion app - UX surfaces + bridge client (#91-E, #91-F)

This commit is contained in:
2026-07-25 20:00:01 +02:00
parent 68a87d1658
commit c65a5a76a9
26 changed files with 1973 additions and 0 deletions

View File

@ -0,0 +1,54 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-feature
android:name="android.hardware.type.watch"
android:required="true" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:label="GameTime"
android:name="${applicationName}"
android:icon="@drawable/ic_launcher"
android:theme="@style/LaunchTheme"
android:usesCleartextTraffic="false">
<uses-library
android:name="com.google.android.wearable"
android:required="true" />
<meta-data
android:name="com.google.android.wearable.standalone"
android:value="false" />
<activity
android:name=".MainActivity"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:exported="true"
android:hardwareAccelerated="true"
android:launchMode="singleTop"
android:taskAffinity=""
android:theme="@style/LaunchTheme"
android:windowSoftInputMode="adjustResize">
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="@style/NormalTheme" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="flutterEmbedding"
android:value="2" />
<service
android:name=".bridge.WatchBridgeListenerService"
android:exported="true">
<intent-filter>
<action android:name="com.google.android.gms.wearable.DATA_CHANGED" />
<action android:name="com.google.android.gms.wearable.MESSAGE_RECEIVED" />
<action android:name="com.google.android.gms.wearable.CAPABILITY_CHANGED" />
<data
android:host="*"
android:pathPrefix="/gametime"
android:scheme="wear" />
</intent-filter>
</service>
</application>
</manifest>

View File

@ -0,0 +1,12 @@
package com.gametime.watch
import com.gametime.watch.bridge.WatchBridgePlugin
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
class MainActivity : FlutterActivity() {
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
WatchBridgePlugin.register(flutterEngine, applicationContext)
}
}

View File

@ -0,0 +1,58 @@
package com.gametime.watch.bridge
import com.google.android.gms.wearable.CapabilityInfo
import com.google.android.gms.wearable.DataEventBuffer
import com.google.android.gms.wearable.MessageEvent
import com.google.android.gms.wearable.WearableListenerService
import org.json.JSONObject
import java.nio.charset.StandardCharsets
class WatchBridgeListenerService : WearableListenerService() {
override fun onDataChanged(dataEvents: DataEventBuffer) {
try {
for (event in dataEvents) {
WatchBridgePlugin.handleDataEvent(event)
}
} finally {
dataEvents.release()
}
}
override fun onMessageReceived(messageEvent: MessageEvent) {
if (messageEvent.path != WatchBridgePlugin.ACK_PATH) {
return
}
val payload = JSONObject(String(messageEvent.data, StandardCharsets.UTF_8))
WatchBridgePlugin.emitAck(payload.toMap())
}
override fun onCapabilityChanged(capabilityInfo: CapabilityInfo) {
if (capabilityInfo.name != WatchBridgePlugin.PHONE_CAPABILITY) {
return
}
WatchBridgePlugin.emitConnection(
isReachable = capabilityInfo.nodes.isNotEmpty(),
requestsResync = capabilityInfo.nodes.isNotEmpty(),
)
if (capabilityInfo.nodes.isNotEmpty()) {
WatchBridgePlugin.requestLatestProjection(applicationContext)
}
}
override fun onCreate() {
super.onCreate()
WatchBridgePlugin.requestCapabilityRefresh(applicationContext)
WatchBridgePlugin.requestLatestProjection(applicationContext)
}
}
private fun JSONObject.toMap(): Map<String, Any?> {
val output = linkedMapOf<String, Any?>()
val keys = keys()
while (keys.hasNext()) {
val key = keys.next()
val value = get(key)
output[key] = if (value == JSONObject.NULL) null else value
}
return output
}

View File

@ -0,0 +1,242 @@
package com.gametime.watch.bridge
import android.content.Context
import android.net.Uri
import com.google.android.gms.wearable.CapabilityClient
import com.google.android.gms.wearable.DataEvent
import com.google.android.gms.wearable.DataMapItem
import com.google.android.gms.wearable.Wearable
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import org.json.JSONArray
import org.json.JSONObject
import java.nio.charset.StandardCharsets
object WatchBridgePlugin {
private const val METHOD_CHANNEL = "gametime.watch_bridge/methods"
private const val PROJECTION_CHANNEL = "gametime.watch_bridge/projections"
private const val ACK_CHANNEL = "gametime.watch_bridge/acks"
private const val CONNECTION_CHANNEL = "gametime.watch_bridge/connection"
const val COMMAND_PATH = "/gametime/watch/command"
const val ACK_PATH = "/gametime/phone/ack"
const val STATE_PATH = "/gametime/phone/projection"
const val PHONE_CAPABILITY = "gametime_phone_companion"
private var appContext: Context? = null
private var projectionSink: EventChannel.EventSink? = null
private var ackSink: EventChannel.EventSink? = null
private var connectionSink: EventChannel.EventSink? = null
fun register(flutterEngine: FlutterEngine, context: Context) {
appContext = context.applicationContext
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, METHOD_CHANNEL)
.setMethodCallHandler(::handleMethodCall)
EventChannel(flutterEngine.dartExecutor.binaryMessenger, PROJECTION_CHANNEL)
.setStreamHandler(
object : EventChannel.StreamHandler {
override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
projectionSink = events
requestLatestProjection(context.applicationContext)
}
override fun onCancel(arguments: Any?) {
projectionSink = null
}
},
)
EventChannel(flutterEngine.dartExecutor.binaryMessenger, ACK_CHANNEL)
.setStreamHandler(
object : EventChannel.StreamHandler {
override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
ackSink = events
}
override fun onCancel(arguments: Any?) {
ackSink = null
}
},
)
EventChannel(flutterEngine.dartExecutor.binaryMessenger, CONNECTION_CHANNEL)
.setStreamHandler(
object : EventChannel.StreamHandler {
override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
connectionSink = events
requestCapabilityRefresh(context.applicationContext)
}
override fun onCancel(arguments: Any?) {
connectionSink = null
}
},
)
}
fun emitProjection(payload: Map<String, Any?>): Boolean {
val sink = projectionSink ?: return false
sink.success(payload)
return true
}
fun emitAck(payload: Map<String, Any?>): Boolean {
val sink = ackSink ?: return false
sink.success(payload)
return true
}
fun emitConnection(isReachable: Boolean, requestsResync: Boolean) {
connectionSink?.success(
mapOf(
"isReachable" to isReachable,
"requestsResync" to requestsResync,
),
)
}
fun handleDataEvent(event: DataEvent) {
if (event.type != DataEvent.TYPE_CHANGED ||
event.dataItem.uri.path != STATE_PATH
) {
return
}
val projectionJson = DataMapItem.fromDataItem(event.dataItem)
.dataMap
.getString("projectionJson")
?: return
emitProjection(JSONObject(projectionJson).toMap())
}
private fun handleMethodCall(call: MethodCall, result: MethodChannel.Result) {
val context = appContext
if (context == null) {
result.error("watch_bridge_unavailable", "Application context unavailable.", null)
return
}
when (call.method) {
"sendCommand" -> sendCommand(context, call.arguments, result)
"requestCapabilityRefresh" -> {
requestCapabilityRefresh(context)
result.success(null)
}
"requestResync" -> {
requestLatestProjection(context)
requestCapabilityRefresh(context)
result.success(null)
}
else -> result.notImplemented()
}
}
private fun sendCommand(
context: Context,
arguments: Any?,
result: MethodChannel.Result,
) {
val map = arguments as? Map<*, *>
if (map == null) {
result.error("invalid_command", "Command payload must be a map.", null)
return
}
val payload = JSONObject(map).toString().toByteArray(StandardCharsets.UTF_8)
Wearable.getCapabilityClient(context)
.getCapability(PHONE_CAPABILITY, CapabilityClient.FILTER_REACHABLE)
.addOnSuccessListener { capability ->
val nodes = capability.nodes.toList()
if (nodes.isEmpty()) {
emitConnection(isReachable = false, requestsResync = false)
result.error("phone_unreachable", "No reachable phone companion.", null)
return@addOnSuccessListener
}
var remaining = nodes.size
var failed = false
for (node in nodes) {
Wearable.getMessageClient(context)
.sendMessage(node.id, COMMAND_PATH, payload)
.addOnSuccessListener {
remaining -= 1
if (remaining == 0 && !failed) {
emitConnection(isReachable = true, requestsResync = false)
result.success(null)
}
}
.addOnFailureListener { error ->
if (failed) {
return@addOnFailureListener
}
failed = true
emitConnection(isReachable = false, requestsResync = false)
result.error("send_command_failed", error.message, null)
}
}
}
.addOnFailureListener { error ->
emitConnection(isReachable = false, requestsResync = false)
result.error("capability_lookup_failed", error.message, null)
}
}
fun requestCapabilityRefresh(context: Context) {
Wearable.getCapabilityClient(context)
.getCapability(PHONE_CAPABILITY, CapabilityClient.FILTER_REACHABLE)
.addOnSuccessListener { capability ->
emitConnection(
isReachable = capability.nodes.isNotEmpty(),
requestsResync = capability.nodes.isNotEmpty(),
)
}
.addOnFailureListener {
emitConnection(isReachable = false, requestsResync = false)
}
}
fun requestLatestProjection(context: Context) {
val uri = Uri.Builder()
.scheme("wear")
.path(STATE_PATH)
.build()
Wearable.getDataClient(context)
.getDataItems(uri)
.addOnSuccessListener { buffer ->
try {
for (item in buffer) {
val projectionJson = DataMapItem.fromDataItem(item)
.dataMap
.getString("projectionJson")
?: continue
emitProjection(JSONObject(projectionJson).toMap())
}
} finally {
buffer.release()
}
}
}
}
private fun JSONObject.toMap(): Map<String, Any?> {
val output = linkedMapOf<String, Any?>()
val keys = keys()
while (keys.hasNext()) {
val key = keys.next()
output[key] = unwrapJsonValue(get(key))
}
return output
}
private fun JSONArray.toList(): List<Any?> {
val output = mutableListOf<Any?>()
for (index in 0 until length()) {
output.add(unwrapJsonValue(get(index)))
}
return output
}
private fun unwrapJsonValue(value: Any?): Any? {
return when (value) {
JSONObject.NULL -> null
is JSONObject -> value.toMap()
is JSONArray -> value.toList()
else -> value
}
}

View File

@ -0,0 +1,12 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="48dp"
android:height="48dp"
android:viewportWidth="48"
android:viewportHeight="48">
<path
android:fillColor="#080A12"
android:pathData="M24,2a22,22 0,1 0,0.1 0z" />
<path
android:fillColor="#D72638"
android:pathData="M13,12h22v6H22v5h11v6H22v7h-9z" />
</vector>

View File

@ -0,0 +1,3 @@
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@android:color/black" />
</layer-list>

View File

@ -0,0 +1,11 @@
<resources>
<style name="LaunchTheme" parent="@android:style/Theme.DeviceDefault.NoActionBar">
<item name="android:windowBackground">@drawable/launch_background</item>
<item name="android:windowIsTranslucent">false</item>
</style>
<style name="NormalTheme" parent="@android:style/Theme.DeviceDefault.NoActionBar">
<item name="android:windowBackground">#080A12</item>
<item name="android:windowIsTranslucent">false</item>
</style>
</resources>

View File

@ -0,0 +1,9 @@
<resources>
<style name="LaunchTheme" parent="@android:style/Theme.DeviceDefault.NoActionBar">
<item name="android:windowBackground">@drawable/launch_background</item>
</style>
<style name="NormalTheme" parent="@android:style/Theme.DeviceDefault.NoActionBar">
<item name="android:windowBackground">#080A12</item>
</style>
</resources>

View File

@ -0,0 +1,5 @@
<resources>
<string-array name="android_wear_capabilities">
<item>gametime_watch_companion</item>
</string-array>
</resources>