We're making some changes to the Google Fit APIs. Learn about how these changes might affect your app. Read our new policy.

Record Fitness Data

The Recording API enables your app to request automated storage of sensor data in a battery- efficient manner by creating subscriptions. A subscription is associated with an Android app and consists of a fitness data type or a specific data source.

You can create multiple subscriptions for different data types or data sources in your app. Google Fit stores fitness data from active subscriptions even when your app is not running and restores these subscriptions when the system restarts.

The recorded data is available in the user's fitness history. If you also want to show the data in your app in real time, you need to use the Sensors API together with the Recording API. To record fitness data with session metadata, you can use the Sessions API.

Subscribe to fitness data

To request background collection of sensor data in your app, use the RecordingClient.subscribe method:

Fitness.getRecordingClient(this, GoogleSignIn.getAccountForExtension(this, fitnessOptions))
    // This example shows subscribing to a DataType. Alternatively, a DataSource can be used.
    .subscribe(DataType.TYPE_STEP_COUNT_DELTA)
    .addOnSuccessListener {
        Log.i(TAG, "Successfully subscribed!")
    }
    .addOnFailureListener { e ->
        Log.w(TAG, "There was a problem subscribing.", e)
    }

If the subscription is added successfully, Google Fit will store fitness data of type TYPE_STEP_COUNT_DELTA in the fitness history on behalf of your app. This subscription will appear in the list of active subscriptions for your app. To remove this subscription, use the RecordingClient.unsubscribe method.

To subscribe to more types of fitness data in your app, follow the steps in the example above providing a different fitness data type each time.

List active subscriptions

To get a list of the active subscriptions for your app, use the RecordingClient.listSubscriptions method:

Fitness.getRecordingClient(this, GoogleSignIn.getAccountForExtension(this, fitnessOptions))
    .listSubscriptions()
    .addOnSuccessListener { subscriptions ->
        for (sc in subscriptions) {
            val dt = sc.dataType
            Log.i(TAG, "Active subscription for data type: ${dt.name}")
        }
    }

Unsubscribe from fitness data

To stop collecting sensor data in your app, use the RecordingClient.unsubscribe method:

Fitness.getRecordingClient(this, GoogleSignIn.getAccountForExtension(this, fitnessOptions))
    // This example shows unsubscribing from a DataType. A DataSource should be used where the
    // subscription was to a DataSource. Alternatively, a Subscription object can be used.
    .unsubscribe(DataType.TYPE_STEP_COUNT_DELTA)
    .addOnSuccessListener {
        Log.i(TAG,"Successfully unsubscribed.")
    }
    .addOnFailureListener { e->
        Log.w(TAG, "Failed to unsubscribe.")
    }