For the complete documentation index, see llms.txt. This page is also available as Markdown.

Android (Kotlin)

Connections

The Android SDK supports the following connection types:

Value
Description

Connections.SAMSUNG

Samsung Health, read via Health Connect (filtered to Samsung Health data only)

Connections.HEALTH_CONNECT

Health Connect (reads all data sources)

Connections.GOOGLE_FIT

Google Fit (via Health Connect, filtered to Google Fit data only)

All three connections read through Health Connect and request the same Health Connect permissions. HEALTH_CONNECT returns data from all apps that write to Health Connect; SAMSUNG and GOOGLE_FIT return only data originating from the Samsung Health and Google Fit apps respectively.

CustomPermissions

Use these to request a subset of permissions instead of all available ones. When not specified, all permissions from your developer scopes are requested. The tables below show what each value requests; see Permissions mapping for the full cross-platform reference.

On Android, the HEALTH_CONNECT, SAMSUNG and GOOGLE_FIT connections all read through Health Connect and request the same Health Connect permissions. They differ only in which data they return:

  • HEALTH_CONNECT returns data from all apps that write to Health Connect.

  • SAMSUNG returns only data written by the Samsung Health app.

  • GOOGLE_FIT returns only data written by the Google Fit app.

So the permission prompt a user sees is identical across the three; the filtering happens when Terra reads the data.

A dash (—) means the value is not supported on Health Connect and requests no data, even if you pass it.

Activity & workouts

CustomPermissions value

Health Connect record(s) requested

WORKOUT_TYPE

Exercise session

ACTIVITY_SUMMARY

Exercise session, Active calories, Total calories, Distance

ACTIVE_DURATIONS

Exercise session

CALORIES

Active calories, Total calories

BASAL_ENERGY_BURNED

Basal metabolic rate

STEPS

Steps

FLIGHTS_CLIMBED

Floors climbed

EXERCISE_DISTANCE

Distance

SWIMMING_SUMMARY

LOCATION

SPEED

Speed

POWER

Power

MINDFULNESS

Exercise session

Heart & cardiovascular

CustomPermissions value

Health Connect record(s) requested

HEART_RATE

Heart rate

RESTING_HEART_RATE

Resting heart rate, Heart rate

HEART_RATE_VARIABILITY

Heart rate variability (RMSSD)

INTERBEAT

ELECTROCARDIOGRAM

VO2MAX

VO₂ max

BLOOD_PRESSURE

Blood pressure

Vitals

CustomPermissions value

Health Connect record(s) requested

RESPIRATORY_RATE

Respiratory rate

OXYGEN_SATURATION

Oxygen saturation

BLOOD_GLUCOSE

Blood glucose

BODY_TEMPERATURE

Body temperature

Body measurements

CustomPermissions value

Health Connect record(s) requested

HEIGHT

Height

WEIGHT

Weight

BMI

Weight, Height

BODY_FAT

Body fat

LEAN_BODY_MASS

Lean body mass

Sleep

CustomPermissions value

Health Connect record(s) requested

SLEEP_ANALYSIS

Sleep session

Nutrition

CustomPermissions value

Health Connect record(s) requested

NUTRITION_* (all macro/micronutrient values)

Nutrition

NUTRITION_WATER

Hydration

Reproductive health

CustomPermissions value

Health Connect record(s) requested

MENSTRUATION

Menstruation flow (+ Menstruation period on Android 14+)

Profile

CustomPermissions value

Health Connect record(s) requested

GENDER

DATE_OF_BIRTH

Utility functions

isHealthConnectAvailable

Checks if Health Connect is available on the device. This is a local check with no network call.

  • context: Context ➡ Activity context.

Returns true if the Health Connect SDK is available, false if not installed or needs updating. Call this before initConnection with Health Connect-based connections to verify availability.

openHealthConnect

Opens the Health Connect settings screen where users can manage app permissions.

  • context: Context ➡ Activity context. May throw ActivityNotFoundException if Health Connect is not installed.

Initialization

instance

Creates and authenticates a TerraManager instance. This makes a network call to Terra's servers to validate your developer ID and retrieve your account configuration (webhook intervals, scopes, existing users).

If existing users are found for this device, the SDK automatically reconnects them and (if schedulerOn was enabled) enqueues background data fetch jobs via WorkManager.

  • devId: String ➡ Your developer ID from the Terra Dashboard.

  • referenceId: String? ➡ An identifier for your app's user. This value appears as reference_id in webhook payloads and API responses, allowing you to map Terra users back to your own user system.

  • context: Context ➡ The activity context. Should be an AppCompatActivity for permission dialog support.

  • completion: (TerraManager, TerraError?) -> Unit ➡ Called when initialization completes. You must wait for this callback before calling any other SDK function. Check the TerraError? parameter — a TerraManager is always returned, but it may not be functional if an error occurred.

Possible errors:

Error
Cause

InvalidDevId

The devId is not recognized by Terra

UnexpectedError

Network failure or unexpected server response

TerraManager Instance methods

Connection setup/management

initConnection

Authenticates a new user connection with Terra's servers and triggers the platform permission dialog. This makes a network call and shows the Health Connect permission dialog (for Samsung/Google Fit/Health Connect connections).

This function should only be called once per user/connection type. On subsequent app launches, Terra.instance will automatically reconnect existing users.

  • connection: Connections ➡ The connection type to initialize.

  • token: String ➡ A single-use authentication token generated from your backend server via the Generate Authentication Token endpoint. Each token can only be used once.

  • context: Context ➡ Activity context (required for the permission dialog).

  • (Optional) customPermissions: Set<CustomPermissions> ➡ Request specific Health Connect permissions. When empty, defaults to all permissions from your developer scopes.

  • schedulerOn: Boolean ➡ Enables automatic background data fetching. Defaults to true. When enabled, the SDK uses WorkManager to periodically fetch new data and send it to your webhook. Default intervals: activity every 20 minutes, daily/body/sleep/nutrition every 8 hours. Intervals are configurable server-side.

  • completion: (Boolean, TerraError?) -> Unit ➡ Called when the connection is established (or fails).

Possible errors:

Error
Cause

InvalidDevId

Developer ID not recognized

InvalidAuthToken

Token is invalid or already used

UserLimitExceeded

Your plan's user limit has been reached

NoInternet

Network request failed

HealthConnectUnavailable

Health Connect is not installed or available

TerraClassNotInitiated

Terra.instance was not called first

getUserId

Returns the Terra user ID for a connection, or null if no connection exists. This is a synchronous, local read with no network call.

The returned user_id is the same identifier used in webhook payloads, API requests, and the Terra dashboard.

  • type: Connections ➡ The connection to retrieve the user ID for.

Returns null when:

  • initConnection was never called for this connection type

  • No existing user was found during Terra.instance initialization

  • The connection failed

checkAuth

Checks whether a connection is authenticated by making a network call to Terra's servers.

  • connection: Connections ➡ The connection type to check.

  • callback: (Boolean) -> Unittrue if the connection is authenticated on the server, false otherwise (including network failures).

allGivenPermissions

Retrieves the set of Health Connect permissions currently granted to your app. Returns permission name strings like "READ_HEART_RATE", "READ_STEPS", "WRITE_WEIGHT", etc.

  • completion: (Set<String>) -> Unit ➡ Called with the set of granted permission names.

Data Retrieval

All data retrieval functions make network calls — even with toWebhook = false, the SDK sends data to Terra's normalization servers and returns the normalized result.

Each function accepts dates as either Date or Long (Unix timestamp in seconds).

toWebhook behavior:

Both paths require network connectivity.

toWebhook

What happens

Completion returns

true (default)

Data is fetched from Health Connect and sent to your webhook destination

A reference ID string only (not the data itself)

false

Data is fetched, sent to Terra for normalization, and the normalized payload is returned locally

The full normalized data payload

getActivity

Retrieves workout and exercise session data (heart rate, speed, power, cadence, distance, calories, GPS routes, steps, etc.).

getDaily

Retrieves daily summary data (total steps, calories, distance, resting heart rate, HRV, floors climbed, SpO2, etc.).

getSleep

Retrieves sleep session data (sleep stages, duration, heart rate, HRV, SpO2, respiratory rate). Sleep stages: unknown, awake, sleeping, out of bed, light, deep, REM.

getBody

Retrieves body measurement data (weight, height, BMI, body fat, heart rate, HRV, blood pressure, blood glucose, SpO2, lean body mass, bone mass, body temperature, basal metabolic rate).

getNutrition

Retrieves nutrition and meal data (macronutrients, micronutrients, water intake, individual meals with meal type).

Completion parameters (same structure for all data getters):

  • Booleantrue if the request succeeded.

  • Payload? ➡ When toWebhook = true, contains only a reference string. When toWebhook = false, contains the full normalized data. null on failure.

  • TerraError? ➡ Describes the error. Possible values: Unauthorised (no connection initialized), UnSupportedResource (unsupported data type for this connection).

getMenstruation and getAthlete are not available on the Android TerraManager. Menstruation data can be accessed via the server-side REST API if the user's provider supports it.

subscribe

Registers for real-time data updates. Currently only STEPS is fully supported on Android — other data types are saved to preferences but do not trigger updates at runtime.

  • forDataTypes: Set<DataTypes> ➡ Data types to subscribe to. Available values: STEPS, HEART_RATE, CALORIES, DISTANCE.

For STEPS, the SDK registers a periodic WorkManager job (every 15 minutes) that reads the hardware step counter and calls Terra.updateHandler with the step count delta.

Before calling subscribe, you must set the update handler:

Last updated

Was this helpful?