处理锻炼事件

健康服务支持 ExerciseEvents,它会在运动期间发生事件时通知您的应用并提供关联的元数据。

添加依赖项

使用运动事件时,需要最新版本的健康服务 SDK。

如需添加健康服务的依赖项,您必须将 Google Maven 制品库添加到项目中。如需了解相关信息,请参阅 Google 的 Maven 制品库

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

Groovy

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

Kotlin

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

检查功能

与健康服务中的所有运动和数据类型一样,请在启动时检查功能。尤其是对于 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!")
        }
      }
    }
  }
}