添加运动路线

运动路线允许用户跟踪与相关运动活动相关的 GPS 路线,并与其他应用共享其锻炼的地图。

本指南概述了应用如何在运动会话的一部分中获得写入路线数据的权限。

以下是运动路线的读写功能的简要概述

  1. 应用为运动路线创建新的写入权限。
  2. 插入是通过将路线作为其字段写入运动会话来完成的。
  3. 读取
    1. 对于会话所有者,数据是使用会话读取访问的。
    2. 来自第三方应用,通过允许用户授予路线的一次性读取权限的对话框。

权限

运动路线有其自己的运行时写入权限(android.permission.health.WRITE_EXERCISE_ROUTE)。

要向您的应用添加运动路线功能,请首先请求特定数据类型的写入权限。

Android 14 权限请求

Android 14 permission request

Android 13 权限请求

Android 13 permission request

您还需要声明运动权限,因为每条路线都与运动会话相关联(一个会话 = 一次锻炼)。

以下是您需要声明才能写入运动路线的权限

<application>
  <uses-permission
android:name="android.permission.health.WRITE_EXERCISE_ROUTE" />
  <uses-permission
android:name="android.permission.health.WRITE_EXERCISE" />
...
</application>

要读取运动路线,您需要请求以下权限

<application>
  <uses-permission
android:name="android.permission.health.READ_EXERCISE_ROUTES" />
  <uses-permission
android:name="android.permission.health.READ_EXERCISE" />
...
</application>

要请求权限,请在首次将您的应用连接到 Health Connect 时使用 PermissionController.createRequestPermissionResultContract() 方法。您可能想要请求的一些权限包括

  • 读取健康数据,包括路线数据:HealthPermission.getReadPermission(ExerciseSessionRecord::class)
  • 写入健康数据,包括路线数据:HealthPermission.getWritePermission(ExerciseSessionRecord::class)
  • 写入运动路线数据:HealthPermission.PERMISSION_WRITE_EXERCISE_ROUTE

读取和写入路线数据

应用通过将路线作为字段写入会话来插入路线。

如果用户没有写入权限并且未设置路线,则路线不会更新。

如果您的应用具有路线写入权限并尝试通过传入没有路线的会话对象来更新会话,则现有路线将被删除。

每当您的应用需要读取第三方应用提供的路线数据时,都会显示一个对话框,询问用户是否允许读取操作。

从会话请求路线

以下是如何在 Health Connect 中读取会话并从该会话请求路线的方法

suspend fun readExerciseSessionAndRoute() {
    val grantedPermissions =
        healthConnectClient.permissionController.getGrantedPermissions()
    if (!grantedPermissions.contains(
          HealthPermission.getReadPermission(ExerciseSessionRecord::class))) {
        // The user doesn't allow the app to read exercise session data.
        return
    }

    val readResponse =
      healthConnectClient.readRecords(
        ReadRecordsRequest(
          ExerciseSessionRecord::class,
          TimeRangeFilter.between(startTime, endTime)
        )
      )
    val exerciseRecord = readResponse.records.first()

    // See https://developer.android.com/training/basics/intents/result#launch
    // for appropriately handling ActivityResultContract.
    val requestExerciseRouteLauncher = fragment.registerForActivityResul
    (ExerciseRouteRequestContract()) { exerciseRoute: ExerciseRoute? ->
            if (exerciseRoute != null) {
                displayExerciseRoute(exerciseRoute)
            } else {
                // Consent was denied
            }
        }

    val exerciseSessionRecord =
      healthConnectClient.readRecord(ExerciseSessionRecord::class, recordId).record

    when (val exerciseRouteResult = exerciseSessionRecord.exerciseRouteResult) {
        is ExerciseRouteResult.Data ->
            displayExerciseRoute(exerciseRouteResult.exerciseRoute)
        is ExerciseRouteResult.ConsentRequired ->
            requestExerciseRouteLauncher.launch(recordId)
        is ExerciseRouteResult.NoData -> Unit // No exercise route to show
        else -> Unit
    }
  }

  fun displayExerciseRoute(route: ExerciseRoute?) {
    val locations = route.route.orEmpty()
    for (location in locations) {
      // Handle location.
    }
  }

从会话写入路线

以下代码演示了如何录制包含锻炼路线的会话。

suspend fun InsertExerciseRoute(healthConnectClient: HealthConnectClient) {
    val grantedPermissions =
        healthConnectClient.permissionController.getGrantedPermissions()
    if (!grantedPermissions.contains(
          getWritePermission(ExerciseSessionRecord::class))) {
        // The user doesn't allow the app to write exercise session data.
        return
    }

    val sessionStartTime = Instant.parse("2023-01-01T10:00:00.00Z")
    val sessionDuration = Duration.ofMinutes(20)

    val exerciseRoute =
      if (getPermissions.contains(PERMISSION_EXERCISE_ROUTE_WRITE) {
        ExerciseRoute(
          listOf(
            ExerciseRoute.Location(
              time = sessionStartTime
              latitude = 6.5483
              longitude = 0.5488
              horizontalAccuracy = Length.meters(2.0)
              verticalAccuracy = Length.meters(2.0),
              altitude = Length.meters(9.0)
            ),
            ExerciseRoute.Location(
              time = sessionStartTime.plus(sessionDuration)
              latitude = 6.4578
              longitude = 0.6577
              horizontalAccuracy = Length.meters(2.0)
              verticalAccuracy = Length.meters(2.0),
              altitude = Length.meters(9.2)
            )
          )
        )
      } else {
        // The user doesn't allow the app to write exercise route data.
        null
      }

    val exerciseSessionRecord =
        ExerciseSessionRecord(
            startTime = /* starting time in milliseconds */,
            startZoneOffset = ZoneOffset.UTC,
            endTime = sessionStartTime.plus(sessionDuration),
            endZoneOffset = ZoneOffset.UTC,
            exerciseType = ExerciseSessionRecord.EXERCISE_TYPE_BIKING,
            title = "Morning Bike Ride",
            exerciseRoute = exerciseRoute
        )

    healthConnectClient.insertRecords(listOf(exerciseSessionRecord))
}