Health service


1.Passive Experiences


2.Active Experiences


アクティブ-インスタントフィードバック.
パッシブ:非インスタント・データを使用します.
*基本設定.
モジュールの構築.gradleでは以下のように宣言します.
dependencies {
  implementation 'androidx.health:health-services-client:1.0.0-alpha02'
  // For Kotlin, this library helps bridge between Futures and coroutines.
  implementation "com.google.guava:guava:30.1.1-android"
  implementation "androidx.concurrent:concurrent-futures-ktx:1.1.0"
}
manifestで次のように宣言します.
<queries>
    <package android:name="com.google.android.wearable.healthservices" />
</queries>
デバイスが必要な機能を提供しているかどうかを確認する必要があります.
val healthClient = HealthServices.getClient(this /*context*/)
val passiveMonitoringClient = healthClient.passiveMonitoringClient
lifecycleScope.launchWhenCreated {
    val capabilities = passiveMonitoringClient.capabilities.await()
    // Supported types for passive data collection
    supportsHeartRate =
        DataType.HEART_RATE_BPM in capabilities.supportedDataTypesPassiveMonitoring
    // Supported types for PassiveGoals
    supportsStepsGoal =
        DataType.STEPS in capabilities.supportedDataTypesEvents
}
この場合、HEART RATE BPMとSTEPが提供されているかを確認します.
*capabilityを出力すると、デバイスがどのような機能を提供しているかがわかります.
健康データの変化に伴い
BroadcastReceiverを実装し、manifestに発表します.
class BackgroundDataReceiver : BroadcastReceiver() {
   override fun onReceive(context: Context, intent: Intent) {
       // Check that the Intent is for passive data
       if (intent?.action != PassiveMonitoringUpdate.ACTION_DATA) {
           return
       }
       val update = PassiveMonitoringUpdate.fromIntent(intent) ?: return

       // List of available data points
       val dataPoints = update.dataPoints

       // List of available user state info
       val userActivityInfoList = update.userActivityInfoUpdates
   }
}
<receiver
   android:name=".BackgroundDataReceiver"
   android:exported="true">
   <intent-filter>
       <action android:name="hs.passivemonitoring.DATA" />
   </intent-filter>
</receiver>
 
Receiverを登録する場合は、次の操作を行います.
HEART RATE BPM、STEP変更時にreceiverからデータを受信できます.(受動的なので少し時間差があります)
val dataTypes = setOf(DataType.HEART_RATE_BPM, DataType.STEPS)
val config = PassiveMonitoringConfig.builder()
   .setDataTypes(dataTypes)
   .setComponentName(ComponentName(context, BackgroundDataReceiver::class.java))
   // To receive UserActivityState updates, ACTIVITY_RECOGNITION permission is required.
   .setShouldIncludeUserActivityState(true)
   .build()
lifecycleScope.launch {
   HealthServices.getClient(context)
       .passiveMonitoringClient
       .registerDataCallback(config)
       .await()
}
リファレンス
https://github.com/android/health-samples
https://developer.android.com/training/wearables/health-services