處理運動事件

健康照護服務支援 ExerciseEvents,可在運動期間發生特定事件時通知應用程式,並提供相關中繼資料。

新增依附元件

使用運動事件需要最新版的 Health Services 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!")
        }
      }
    }
  }
}