watch: collect direct distance/floors/elevation/calories via Health Services
- Commit
ecec4747f488fac5ea0a33e73ee3a1093a585e4a- Author
- Vayun Mathur <[email protected]>
- When
- 2026-07-06 16:15 UTC (5 months ago)
- Parents
3760849
Replace barometer collection with Wear OS Health Services passive monitoring for OEM-calibrated daily totals. Adds androidx.health:health-services-client to the watch module only (no GMS/Play). MetricType drops Pressure and adds Distance/Floors/Elevation/Calories; a new HealthServicesCollector registers a capability-gated PassiveListenerCallback and persists each running daily total through the existing BLE pipeline. HR/Steps and stationary/motion tagging are unchanged.
Diff
gradle/libs.versions.toml
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex 8667a21bdd..42c805fa04 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -53,6 +53,7 @@ biometric = "1.2.0-alpha05" pdfViewer = "1.0.0-alpha19" glance = "1.1.1" connectClient = "1.2.0-alpha04"+healthServicesClient = "1.1.0-alpha05" cryptographyCore = "0.6.0" libphonenumber = "9.0.32" material3AdaptiveNavigationSuite = "1.4.0"@@ -164,6 +165,9 @@ kotlinx-datetime = { module = "org.jetbrains.kotlinx:kotlinx-datetime", version. # Specialized Utilities androidx-connect-client = { module = "androidx.health.connect:connect-client", version.ref = "connectClient" }+# Wear OS Health Services — direct, OEM-calibrated on-watch measurements. Not+# Google Play / GMS; safe to keep isolated to the watch module.+androidx-health-services-client = { module = "androidx.health:health-services-client", version.ref = "healthServicesClient" } cryptography-core = { module = "dev.whyoleg.cryptography:cryptography-core", version.ref = "cryptographyCore" } cryptography-provider-jdk = { module = "dev.whyoleg.cryptography:cryptography-provider-jdk", version.ref = "cryptographyCore" } jaudiotagger = { module = "net.jthink:jaudiotagger", version.ref = "jaudiotagger" }
watch/watch/build.gradle.kts
diff --git a/watch/watch/build.gradle.kts b/watch/watch/build.gradle.ktsindex 343a5b6072..57cddce380 100644--- a/watch/watch/build.gradle.kts+++ b/watch/watch/build.gradle.kts@@ -10,5 +10,6 @@ android { } dependencies {+ implementation(libs.androidx.health.services.client) implementRoom(libs) }
watch/watch/src/main/java/com/vayunmathur/watch/watch/data/SensorRecord.kt
diff --git a/watch/watch/src/main/java/com/vayunmathur/watch/watch/data/SensorRecord.kt b/watch/watch/src/main/java/com/vayunmathur/watch/watch/data/SensorRecord.ktindex 749e9b25e1..c577ea8a56 100644--- a/watch/watch/src/main/java/com/vayunmathur/watch/watch/data/SensorRecord.kt+++ b/watch/watch/src/main/java/com/vayunmathur/watch/watch/data/SensorRecord.kt@@ -14,8 +14,12 @@ import kotlinx.coroutines.flow.Flow enum class MetricType { HeartRate, Steps,- Pressure, Motion,+ // Directly-measured daily totals from Wear OS Health Services.+ Distance,+ Floors,+ Elevation,+ Calories, } @Entity@@ -24,7 +28,8 @@ data class SensorRecord( val type: MetricType, val timestamp: Long, // For HeartRate: the bpm reading. For Steps: cumulative counter value.- // For Pressure: hPa. For Motion: 1.0 = stationary, 0.0 = moving.+ // For Motion: 1.0 = stationary, 0.0 = moving. For Distance/Floors/Elevation/+ // Calories: the running daily total from Health Services. val value: Double, // For Steps: increment since the previous reading. Otherwise 0. val delta: Double = 0.0,
watch/watch/src/main/java/com/vayunmathur/watch/watch/service/HealthServicesCollector.kt
diff --git a/watch/watch/src/main/java/com/vayunmathur/watch/watch/service/HealthServicesCollector.kt b/watch/watch/src/main/java/com/vayunmathur/watch/watch/service/HealthServicesCollector.ktnew file mode 100644index 0000000000..cf03a57524--- /dev/null+++ b/watch/watch/src/main/java/com/vayunmathur/watch/watch/service/HealthServicesCollector.kt@@ -0,0 +1,123 @@+package com.vayunmathur.watch.watch.service++import android.content.Context+import android.util.Log+import androidx.health.services.client.HealthServices+import androidx.health.services.client.PassiveListenerCallback+import androidx.health.services.client.PassiveMonitoringClient+import androidx.health.services.client.data.DataPointContainer+import androidx.health.services.client.data.DataType+import androidx.health.services.client.data.PassiveListenerConfig+import com.vayunmathur.watch.watch.data.MetricType+import com.vayunmathur.watch.watch.data.SensorDao+import com.vayunmathur.watch.watch.data.SensorRecord+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch+import java.util.concurrent.Executor++/**+ * Collects directly-measured, OEM-calibrated daily totals (distance, floors,+ * elevation gain, calories) from Wear OS Health Services via passive monitoring+ * and persists each new running daily total as a [SensorRecord] for the BLE+ * pipeline to stream to the phone.+ *+ * Health Services is a Wear OS platform component and does not pull in Google+ * Play Services / Fitness, so it is safe to keep on the watch alongside the+ * Health Connect phone app.+ */+class HealthServicesCollector(+ context: Context,+ private val dao: SensorDao,+ private val scope: CoroutineScope,+) {+ private val client: PassiveMonitoringClient =+ HealthServices.getClient(context.applicationContext).passiveMonitoringClient++ private var registered = false++ // Run future listeners inline; work done is trivial (read result, register).+ private val directExecutor = Executor { it.run() }++ fun start() {+ val future = client.getCapabilitiesAsync()+ future.addListener({+ val supported = try {+ future.get().supportedDataTypesPassiveMonitoring+ } catch (e: Exception) {+ Log.e(TAG, "getCapabilities failed", e)+ return@addListener+ }+ val types = DESIRED_TYPES.filter { it in supported }.toSet()+ if (types.isEmpty()) {+ Log.w(TAG, "No supported daily data types for passive monitoring")+ return@addListener+ }+ register(types)+ }, directExecutor)+ }++ private fun register(types: Set<DataType<*, *>>) {+ val config = PassiveListenerConfig.builder()+ .setDataTypes(types)+ .build()+ try {+ client.setPassiveListenerCallback(config, callback)+ registered = true+ } catch (e: Exception) {+ Log.e(TAG, "setPassiveListenerCallback failed", e)+ }+ }++ private val callback = object : PassiveListenerCallback {+ override fun onNewDataPointsReceived(dataPoints: DataPointContainer) {+ val now = System.currentTimeMillis()+ dataPoints.getData(DataType.DISTANCE_DAILY).forEach {+ persist(MetricType.Distance, it.value, now)+ }+ dataPoints.getData(DataType.FLOORS_DAILY).forEach {+ persist(MetricType.Floors, it.value, now)+ }+ dataPoints.getData(DataType.ELEVATION_GAIN_DAILY).forEach {+ persist(MetricType.Elevation, it.value, now)+ }+ dataPoints.getData(DataType.CALORIES_DAILY).forEach {+ persist(MetricType.Calories, it.value, now)+ }+ }+ }++ fun stop() {+ if (!registered) return+ try {+ client.clearPassiveListenerCallbackAsync()+ } catch (e: Exception) {+ Log.e(TAG, "clearPassiveListenerCallback failed", e)+ }+ registered = false+ }++ private fun persist(type: MetricType, value: Double, timestamp: Long) {+ val record = SensorRecord(type = type, timestamp = timestamp, value = value)+ scope.launch(Dispatchers.IO) {+ try {+ dao.insert(record)+ } catch (e: Exception) {+ Log.e(TAG, "insert failed", e)+ }+ }+ }++ companion object {+ private const val TAG = "HealthServicesCollector"++ // Direct daily-total metrics. CALORIES_DAILY is total energy (BMR ++ // active); we forward the honest direct value rather than re-deriving.+ private val DESIRED_TYPES: Set<DataType<*, *>> = setOf(+ DataType.DISTANCE_DAILY,+ DataType.FLOORS_DAILY,+ DataType.ELEVATION_GAIN_DAILY,+ DataType.CALORIES_DAILY,+ )+ }+}
watch/watch/src/main/java/com/vayunmathur/watch/watch/service/SensorBackgroundService.kt
diff --git a/watch/watch/src/main/java/com/vayunmathur/watch/watch/service/SensorBackgroundService.kt b/watch/watch/src/main/java/com/vayunmathur/watch/watch/service/SensorBackgroundService.ktindex be56651640..ec52ac475e 100644--- a/watch/watch/src/main/java/com/vayunmathur/watch/watch/service/SensorBackgroundService.kt+++ b/watch/watch/src/main/java/com/vayunmathur/watch/watch/service/SensorBackgroundService.kt@@ -36,11 +36,11 @@ class SensorBackgroundService : Service(), SensorEventListener { private lateinit var sensorManager: SensorManager private lateinit var gattServer: GattServerManager+ private lateinit var healthServices: HealthServicesCollector private var lastHeartRateAt = 0L // The step counter reports a cumulative count since boot; we store deltas. private var lastStepCount = -1.0- private var lastPressureAt = 0L // Current motion state, maintained via the one-shot trigger sensors. @Volatile private var isStationary = false @@ -48,6 +48,7 @@ class SensorBackgroundService : Service(), SensorEventListener { super.onCreate() val db = SensorDatabase.get(this) gattServer = GattServerManager(this, db.sensorDao(), scope)+ healthServices = HealthServicesCollector(this, db.sensorDao(), scope) sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager } @@ -55,6 +56,7 @@ class SensorBackgroundService : Service(), SensorEventListener { startForeground(NOTIFICATION_ID, buildNotification()) registerSensors() gattServer.start()+ healthServices.start() return START_STICKY } @@ -65,9 +67,6 @@ class SensorBackgroundService : Service(), SensorEventListener { sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)?.let { sensorManager.registerListener(this, it, SensorManager.SENSOR_DELAY_NORMAL) }- sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE)?.let {- sensorManager.registerListener(this, it, SensorManager.SENSOR_DELAY_NORMAL)- } // Arm the stationary detector; the two trigger sensors re-arm each other. armStationaryDetect() }@@ -139,13 +138,6 @@ class SensorBackgroundService : Service(), SensorEventListener { ), ) }- Sensor.TYPE_PRESSURE -> {- val hpa = event.values.firstOrNull()?.toDouble() ?: return- if (hpa <= 0.0) return- if (now - lastPressureAt < PRESSURE_INTERVAL_MS) return- lastPressureAt = now- persist(SensorRecord(type = MetricType.Pressure, timestamp = now, value = hpa))- } } } @@ -189,6 +181,7 @@ class SensorBackgroundService : Service(), SensorEventListener { sensorManager.getDefaultSensor(Sensor.TYPE_MOTION_DETECT), ) gattServer.stop()+ healthServices.stop() scope.cancel() super.onDestroy() }@@ -200,7 +193,6 @@ class SensorBackgroundService : Service(), SensorEventListener { private const val CHANNEL_ID = "sensor_collection" private const val NOTIFICATION_ID = 1 private const val HEART_RATE_INTERVAL_MS = 60_000L- private const val PRESSURE_INTERVAL_MS = 30_000L fun start(context: Context) { val intent = Intent(context, SensorBackgroundService::class.java)