本部分介绍如何使用 Google 健身读取当前每日步数数据 Android API 和 Fit REST API。
Android
您的应用程序可以通过调用 读取当前的每日总步数。
HistoryClient.readDailyTotal
、
如以下示例中所示:
Fitness.getHistoryClient(this, GoogleSignIn.getAccountForExtension(this, fitnessOptions)) .readDailyTotal(DataType.TYPE_STEP_COUNT_DELTA) .addOnSuccessListener { result -> val totalSteps = result.dataPoints.firstOrNull()?.getValue(Field.FIELD_STEPS)?.asInt() ?: 0 // Do something with totalSteps } .addOnFailureListener { e -> Log.i(TAG, "There was a problem getting steps.", e) }
每日总值是从当天的午夜开始计算, 当前时区。
要获取与 Google 健身应用相同的每日步数,请使用
com.google.android.gms
应用软件包,如以下示例所示:
val startTime = LocalDate.now().atStartOfDay(ZoneId.systemDefault()) val endTime = LocalDateTime.now().atZone(ZoneId.systemDefault()) val datasource = DataSource.Builder() .setAppPackageName("com.google.android.gms") .setDataType(DataType.TYPE_STEP_COUNT_DELTA) .setType(DataSource.TYPE_DERIVED) .setStreamName("estimated_steps") .build() val request = DataReadRequest.Builder() .aggregate(datasource) .bucketByTime(1, TimeUnit.DAYS) .setTimeRange(startTime.toEpochSecond(), endTime.toEpochSecond(), TimeUnit.SECONDS) .build() Fitness.getHistoryClient(this, GoogleSignIn.getAccountForExtension(this, fitnessOptions)) .readData(request) .addOnSuccessListener { response -> val totalSteps = response.buckets .flatMap { it.dataSets } .flatMap { it.dataPoints } .sumBy { it.getValue(Field.FIELD_STEPS).asInt() } Log.i(TAG, "Total steps: $totalSteps") }
如需详细了解如何使用汇总数据源,请参阅 使用健身历史记录。
REST
您的应用可以从所有数据中读取当前每日总步数
方法是发出 POST
请求并查询
指定时间段的“com.google.step_count.delta
”数据类型。
HTTP 方法
POST
Request URL
https://www.googleapis.com/fitness/v1/users/me/dataset:aggregate
请求正文
{
"aggregateBy": [{
"dataTypeName": "com.google.step_count.delta",
"dataSourceId": "derived:com.google.step_count.delta:com.google.android.gms:estimated_steps"
}],
"bucketByTime": { "durationMillis": 86400000 },
"startTimeMillis": 1438705622000,
"endTimeMillis": 1439310422000
}
Curl 命令
curl \
-X POST \
-H "Content-Type: application/json;encoding=utf-8" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-d @aggregate.json \
https://www.googleapis.com/fitness/v1/users/me/dataset:aggregate