You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何借助Google Fit API获取各类健身活动的步数与卡路里消耗数据?

Hey there! Let’s break down how you can pull activity-specific data—including steps and calorie burn—for Aerobics, Badminton, Boxing, Weight Lifting, and other workouts using the Google Fit API. I’ll walk you through the setup, key concepts, and practical code snippets to make this straightforward.

前期准备工作

Before diving into code, you need to get your environment set up properly:

1. Enable the Google Fit API

Head to the Google Cloud Console, create or select your project, search for "Google Fit API", and enable it. You’ll also need to configure the OAuth consent screen (add the necessary scopes) and create credentials (OAuth client ID) for your target platform (web, Android, iOS).

2. Authenticate with Required Scopes

To read activity and calorie data, you’ll need the https://www.googleapis.com/auth/fitness.activity.read scope. Make sure your auth flow requests this scope and retrieves a valid access token for the user.

核心概念:活动类型与目标数据类型

Google Fit categorizes each workout with a specific activity type constant, and tracks metrics like steps and calories as distinct data types. Here’s what you’ll need for your target activities:

活动类型常量(用于过滤)

  • Aerobics: TYPE_AEROBICS (integer value: 8)
  • Badminton: TYPE_BADMINTON (integer value: 10)
  • Boxing: TYPE_BOXING (integer value: 13)
  • Weight Lifting: TYPE_WEIGHTLIFTING (integer value: 97)

目标数据类型

  • Steps: TYPE_STEP_COUNT_DELTA (aggregated version: AGGREGATE_STEP_COUNT_DELTA for summed session values)
  • Calories Burned: TYPE_CALORIES_EXPENDED (aggregated version: AGGREGATE_CALORIES_EXPENDED)
具体实现:查询活动数据

You can use either the REST API or platform-specific client libraries to fetch data. Let’s cover both approaches.

REST API Example

Send a POST request to the users/dataset:aggregate endpoint. Here’s a sample request body that filters for Aerobics activity and pulls steps + calories over a date range:

{
  "aggregateBy": [
    {
      "dataTypeName": "com.google.step_count.delta",
      "dataSourceId": "derived:com.google.step_count.delta:com.google.android.gms:merge_step_deltas"
    },
    {
      "dataTypeName": "com.google.calories.expended",
      "dataSourceId": "derived:com.google.calories.expended:com.google.android.gms:merge_calories_expended"
    }
  ],
  "bucketByActivitySegment": {
    "activityType": 8, // Aerobics
    "minDurationMillis": 60000 // Only include sessions longer than 1 minute
  },
  "startTimeMillis": 1698844800000, // Replace with your start timestamp (UTC in ms)
  "endTimeMillis": 1698931200000 // Replace with your end timestamp (UTC in ms)
}

To switch to another activity, just update the activityType value (e.g., 10 for Badminton, 13 for Boxing).

Android Client Library Example

If you’re building an Android app, use the Google Fit Android SDK. Here’s a snippet to query aggregated steps and calories for Weight Lifting:

// Define the time range (replace with your start/end timestamps)
long startTime = /* Your start time in ms */;
long endTime = /* Your end time in ms */;

// Build the data read request
DataReadRequest readRequest = new DataReadRequest.Builder()
    .aggregate(DataType.AGGREGATE_STEP_COUNT_DELTA)
    .aggregate(DataType.AGGREGATE_CALORIES_EXPENDED)
    .bucketByActivityType(1, TimeUnit.MINUTES)
    .setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS)
    .build();

// Execute the request and process results
Fitness.getHistoryClient(context, GoogleSignIn.getLastSignedInAccount(context))
    .readData(readRequest)
    .addOnSuccessListener(dataReadResponse -> {
        for (Bucket bucket : dataReadResponse.getBuckets()) {
            int activityType = bucket.getActivity();
            // Filter for Weight Lifting sessions
            if (activityType == FitnessActivities.WEIGHTLIFTING) {
                for (DataSet dataSet : bucket.getDataSets()) {
                    for (DataPoint dataPoint : dataSet.getDataPoints()) {
                        for (Field field : dataPoint.getDataType().getFields()) {
                            float value = dataPoint.getValue(field).asFloat();
                            if (field.getName().equals("steps")) {
                                Log.d("FitData", "Weight Lifting Steps: " + value);
                            } else if (field.getName().equals("calories")) {
                                Log.d("FitData", "Weight Lifting Calories: " + value);
                            }
                        }
                    }
                }
            }
        }
    })
    .addOnFailureListener(e -> Log.e("FitError", "Failed to read data: " + e.getMessage()));
关键技巧:精准过滤活动数据
  • Target specific activities: Always specify the exact activity type ID in your request to avoid mixing data from unrelated workouts.
  • Use aggregated data: Aggregated data types (like AGGREGATE_STEP_COUNT_DELTA) give you summed values per activity session, which is exactly what you need for steps and calorie totals.
  • Filter short sessions: Add a minimum duration (e.g., 1 minute) to exclude accidental, short activity entries that don’t represent actual workouts.
常见问题与注意事项
  • Missing data: If you don’t see data for a specific activity, confirm the user has recorded that workout in Google Fit (either manually or via a connected device).
  • Permission checks: Double-check that your app has the activity.read scope—without it, you’ll get authorization errors.
  • Time zone handling: Timestamps in the API are in UTC, so convert them to the user’s local time zone when displaying results for clarity.

内容的提问来源于stack exchange,提问作者Partha Chakraborty

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:05:36