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

wbrvyc0a  于 2022-11-20  发布在  Android
关注(0)|答案(2)|浏览(141)

我正在尝试从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()获得非聚合数据而不会出现问题。

uqcuzwp8

uqcuzwp81#

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

l2osamch2#

若要依期间进行汇总,您需要使用以LocalDateTime为基础的TimeRangeFilter,并确定您的开始和结束时间都是LocalDateTime类型,而不是Instants类型。

相关问题