ヘルスコネクトの集計データでは、基本的な集計とバケットへのデータの集計を行うことができます。以下のワークフローでは、この 2 つの集計を行う方法について説明します。
基本的な集計: 累積
次の例は、特定のデータ型のデータを集計する方法を示しています。
suspend fun aggregateDistance(client: HealthConnectClient): Double? {
val request = AggregateRequest(
metrics = setOf(Distance.DISTANCE_TOTAL),
timeRangeFilter = TimeRangeFilter.between(START_TIME, END_TIME)
)
val response = client.aggregate(request)
// The result may be null if no data is available to aggregate.
return response.getMetric(Distance.DISTANCE_TOTAL)
}
基本的な集計: 統計
統計集計では、最小値、最大値、平均値を計算します。
統計集計の例を以下に示します。
suspend fun aggregateHROverTime(client: HealthConnectClient): Long? {
val aggregate = client.aggregate(
AggregateRequest(
setOf(HeartRateSeries.BPM_MAX),
timeRangeFilter = TimeRangeFilter.between(START_TIME, END_TIME),
dataOriginFilter = listOf(
DataOrigin("androidx.health.connect.client.sample")
)
)
)
// The result may be null if no data is available to aggregate.
return aggregate.getMetric(HeartRateSeries.BPM_MAX)
}
バケット
ヘルスコネクトでは、データをバケットに集計できます。使用できるバケットには次の 2 種類があります。
- Duration - 各バケットの期間は固定長で設定されます(例: 1 分、1 時間)。
- Period - 各バケットの期間は概念上の単位で設定されます(例: 1 週間、1 か月)。
ヘルスコネクトはバケットのリストを返します。このリストはスパースであるため、バケットにデータが格納されていないと、このリストには含まれません。
ステップを月ごとのバケットで集計する例を以下に示します。
suspend fun aggregateIntoMonths(healthConnectClient: HealthConnectClient) {
val aggregateGroupByPeriodRequest = AggregateGroupByPeriodRequest(
metrics = setOf(Steps.TOTAL),
timeRangeFilter = TimeRangeFilter.between(START_TIME, END_TIME),
timeRangeSlicer = Period.ofMonths(1)
)
val response = healthConnectClient.aggregateGroupByPeriod(
aggregateGroupByPeriodRequest
)
response.forEach { period ->
val totalSteps = period.result.getMetric(Steps.TOTAL) ?: 0L
}
}
Duration
で集計するには、前の方法と同じパターンで行いますが、代わりに aggregateGroupByDuration(request: AggregateGroupByDurationRequest)
メソッドを使用します。