如何在Android Health Connect API中进行聚合搜索



我正在尝试从Google新的Health Connect API:中获取每日累计步数

val request = AggregateGroupByPeriodRequest(
setOf(StepsRecord.COUNT_TOTAL),
TimeRangeFilter.between(Instant.now().minus(10, ChronoUnit.DAYS), Instant.now()),
Period.ofDays(1),
setOf<DataOrigin>())
val response = client.aggregateGroupByPeriod(request)

但我执行的任何聚合查询都会导致以下异常:

java.lang.IllegalStateException: Duration must be set with physical times
at android.os.Parcel.createExceptionOrNull(Parcel.java:3019)
at android.os.Parcel.createException(Parcel.java:2995)
at android.os.Parcel.readException(Parcel.java:2978)
at android.os.Parcel.readException(Parcel.java:2920)
at androidx.health.platform.client.service.IHealthDataService$Stub$Proxy.aggregate(IHealthDataService.java:490)
at androidx.health.platform.client.impl.ServiceBackedHealthDataClient.aggregate$lambda$9(ServiceBackedHealthDataClient.kt:162)
at androidx.health.platform.client.impl.ServiceBackedHealthDataClient.$r8$lambda$sD3sEial4TRJZ0x1SNHmgqr5dxw(Unknown Source:0)
at androidx.health.platform.client.impl.ServiceBackedHealthDataClient$$ExternalSyntheticLambda10.execute(Unknown Source:6)
at androidx.health.platform.client.impl.ipc.Client$3.execute(Client.java:297)
at androidx.health.platform.client.impl.ipc.internal.ServiceConnection.execute(ServiceConnection.java:286)
at androidx.health.platform.client.impl.ipc.internal.ServiceConnection.enqueue(ServiceConnection.java:243)
at androidx.health.platform.client.impl.ipc.internal.ConnectionManager.handleMessage(ConnectionManager.java:148)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.os.HandlerThread.run(HandlerThread.java:67)
Suppressed: kotlinx.coroutines.DiagnosticCoroutineContextException: [StandaloneCoroutine{Cancelling}@850d063, Dispatchers.Main]

有什么想法是什么导致的,或者如何解决它吗?使用client.readRecords(),我可以毫无问题地获得非聚合数据。

https://developer.android.com/guide/health-and-fitness/health-connect/common-workflows/aggregate-data#buckets

示例代码使用了Instant,但您需要使用LocalDateTime。

val startTime = LocalDateTime.now().minusMonths(1)
val endTime = LocalDateTime.now()
val response =
healthConnectClient.aggregateGroupByPeriod(
AggregateGroupByPeriodRequest(
metrics = setOf(StepsRecord.COUNT_TOTAL),
timeRangeFilter = TimeRangeFilter.between(startTime, endTime),
timeRangeSlicer = Period.ofDays(1)
)
)

为了按时段聚合,您需要使用基于LocalDateTime的TimeRangeFilter,并确保开始和结束时间的类型为LocalDateTime而不是Instants。

最新更新