处理运动事件

Health Services 支持 ExerciseEvents,此类事件会在运动期间发生事件时通知您的应用,并提供相关元数据。

添加依赖项

使用运动事件需要最新版本的 Health Services SDK。

如需添加对 Health Services 的依赖项,您必须将 Google Maven 代码库添加到您的项目中。如需了解详情,请参阅Google 的 Maven 代码库

然后,在模块级 build.gradle 文件中添加以下依赖项

Groovy

dependencies {
    implementation "androidx.health:health-services-client:1.1.0-alpha05"
}

Kotlin

dependencies {
    implementation("androidx.health:health-services-client:1.1.0-alpha05")
}

检查功能

与 Health Services 中的所有运动和数据类型一样,请在启动时检查功能。特别是对于 ExerciseEvents,除了请求 ExerciseCapabilities 之外,还应使用 ExerciseTypeCapabilities.supportedExerciseEvents 来验证给定运动支持哪些运动事件。确认特定 ExerciseEvent 受支持后,您还应该使用 getExerciseEventCapabilityDetails 查询运动事件的功能。

以下示例展示了如何查询功能以确认 GOLF_SHOT_EVENT 受支持,然后确认 GOLF_SHOT_EVENT 支持挥杆类型分类。

fun handleCapabilities(capabilities: ExerciseCapabilities) {
  val golfCapabilities = capabilities.typeToCapabilities[ExerciseType.GOLF]
  val golfShotEventSupported =
    golfCapabilities
      ?.supportedExerciseEvents
      ?.contains(ExerciseEventType.GOLF_SHOT_EVENT)
  val golfSwingTypeClassificationSupported =
    golfCapabilities
      ?.getExerciseEventCapabilityDetails(ExerciseEventType.GOLF_SHOT_EVENT)
      ?.isSwingTypeClassificationSupported ?: false
}

在运动中请求运动事件

若要开始运动并将运动事件作为运动的一部分进行请求,请声明运动的 ExerciseConfig 并添加一个用于 exerciseEventType 的字段。

以下示例请求 GOLF 运动中的 GOLF_SHOT_EVENT

val config = ExerciseConfig(
  exerciseType = ExerciseType.GOLF,
  dataTypes = setOf(....),
  // ...
  exerciseEventTypes = setOf(ExerciseEventType.GOLF_SHOT_EVENT),
)

注册运动事件更新

您可以通过应用现有接收运动更新的基础架构,接收 ExerciseEvent 更新。以下示例展示了如何整合对 GolfShotEvent 更新的支持

val callback = object : ExerciseUpdateCallback {
  override fun onExerciseUpdateReceived(update: ExerciseUpdate) {
      ...
  }
  // [ExerciseEvent] intended to come through with low latency and out of
  // band of onExerciseUpdateReceived()
  override fun onExerciseEventReceived(event: ExerciseEvent) {
    when (event) {
      is GolfShotEvent -> {
        if (it.swingType == GolfShotSwingType.PUTT) {
          println("Putt detected!")
        }
      }
    }
  }
}