本節將示範如何使用 Fit 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 Fit 應用程式相同的每日步數,請使用 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
要求網址
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