添加锻炼路线

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

本指南概述了应用如何获得写入锻炼时段路线数据的权限。

以下是锻炼路线的读取和写入功能的简要说明:

  1. 应用会为锻炼路线创建新的写入权限。
  2. 插入的方法是写入一个锻炼时段,并以路线作为字段。
  3. 读取:
    1. 对于时段拥有者,可通过会话读取来访问数据。
    2. 在第三方应用中,通过对话框向用户授予路线的一次性读取权限。

权限

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

如要向应用添加锻炼路线功能,请先请求特定数据类型的写入权限。

Android 14 权限请求

Android 14 权限请求

Android 13 权限请求

Android 13 权限请求

您还必须声明一项锻炼权限,因为每条路线都与锻炼时段(一个时段 = 一次锻炼)相关联。

您需要声明以下权限才能写入锻炼路线:

<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))
}