> For the complete documentation index, see [llms.txt](https://docs.tryterra.co/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.tryterra.co/reference/streaming-api/android-kotlin.md).

# Android SDK

Every type and function in the Android RT SDK.

The Android RT SDK streams data from BLE and ANT+ devices, Wear OS watches and the phone's own sensors through the `TerraRT` class. This page lists its types and functions.

## Connections

```kotlin
enum class Connections {
    BLE,          // Bluetooth Low Energy devices (heart rate monitors, etc.)
    WEAR_OS,      // Wear OS watches via classic Bluetooth
    ANDROID,      // Phone's built-in sensors (accelerometer, gyroscope)
    ANT,          // ANT+ protocol devices
    ALL_DEVICES,  // Combined BLE + ANT scanning/connection
}
```

## DataTypes

```kotlin
enum class DataTypes {
    HEART_RATE, ECG, STEPS, HRV, CALORIES, LOCATION, DISTANCE,
    ACTIVITY, ACCELERATION, GYROSCOPE, FLOORS_CLIMBED, STEPS_CADENCE,
    SPEED, POWER, BIKE_CADENCE, MET, RR_INTERVAL,
    CORE_TEMPERATURE, SKIN_TEMPERATURE
}
```

## Update

Data points delivered via streaming callbacks.

```kotlin
data class Update(
    var ts: String? = null,           // ISO 8601 timestamp
    var `val`: Double? = null,        // Scalar value (e.g. heart rate BPM)
    var type: String? = null,         // Data type identifier (e.g. "HEART_RATE")
    var d: ArrayList<Double>? = null  // Array for multi-axis data (e.g. [x, y, z])
)
```

For scalar metrics (heart rate, steps), the value is in `val`. For vector metrics (acceleration, gyroscope), the values are in `d`. `val` is a Kotlin keyword, so access it with backticks: `` update.`val` ``.

## Device

Represents a discovered BLE/ANT device.

```kotlin
data class Device(
    val deviceId: String,       // Device identifier
    val deviceName: String?,    // Human-readable name (nullable)
)
```

## ConnectedDevice

Represents a currently connected device.

```kotlin
data class ConnectedDevice(
    val id: String,      // Device identifier
    val name: String?,   // Device name (nullable)
    val type: String,    // "BLE", "BT", or "ANT"
)
```

## ConnectionState

```kotlin
enum class ConnectionState {
    DISCONNECTED, CONNECTING, CONNECTED
}
```

## Initialization

### TerraRT

Creates and authenticates a `TerraRT` instance. Makes a network call to Terra. Requests the required Android permissions (Bluetooth, location, activity recognition, body sensors) if not already granted.

```kotlin
class TerraRT(
    devId: String,
    context: Context,
    referenceId: String?,
    completion: (Boolean) -> Unit
)
```

* `devId` ➡ Your developer ID from the [Terra Dashboard](https://dashboard.tryterra.co).
* `context` ➡ Activity context (required for permission dialogs).
* `referenceId` ➡ Optional user identifier in your system. Appears as `reference_id` in webhooks.
* `completion` ➡ `true` if initialization succeeded.

## Connection setup

### initConnection

Authenticates the SDK user with Terra. Makes a network call. Generate the `token` on your backend with [`POST /auth/generateAuthToken`](https://docs.tryterra.co/reference/streaming-api/api-endpoints.md).

```kotlin
fun initConnection(token: String, callback: (Boolean) -> Unit)
```

### getUserId

Returns the Terra user ID, or `null` if not yet initialized. Synchronous, no network call.

```kotlin
fun getUserId(): String?
```

### disconnect

Disconnects from the given connection type.

```kotlin
fun disconnect(type: Connections)
```

## Device scanning

Two `startDeviceScan` overloads cover the scanning workflows:

### startDeviceScan (with device callback)

Starts scanning and calls `deviceCallback` for each discovered device. You then call `connectDevice()` to connect to a chosen device.

```kotlin
fun startDeviceScan(type: Connections,
                    deviceCallback: (Device) -> Unit)
```

### startDeviceScan (with built-in UI)

Starts scanning with automatic connection handling. If `useCache` is `true`, reconnects to a previously paired device. If not found and `showWidgetIfCacheNotFound` is `true`, shows the built-in device picker UI.

```kotlin
fun startDeviceScan(type: Connections,
                    useCache: Boolean = false,
                    showWidgetIfCacheNotFound: Boolean = true,
                    callback: (Boolean) -> Unit = { _ -> })
```

### connectDevice

Connects to a specific `Device` returned from the device-callback `startDeviceScan` overload.

```kotlin
fun connectDevice(device: Device,
                  connectionCallback: (Boolean) -> Unit)
```

### getConnectedDevices

Returns the set of currently connected devices.

```kotlin
fun getConnectedDevices(): Set<ConnectedDevice>
```

## Data streaming

Three `startRealtime` overloads cover the streaming modes:

### startRealtime (server + local)

Streams data to both Terra's WebSocket server and a local `updateHandler` callback.

```kotlin
fun startRealtime(type: Connections,
                  dataTypes: Set<DataTypes> = setOf(),
                  token: String,
                  updateHandler: (Update) -> Unit,
                  connectionCallback: (Boolean) -> Unit = { _ -> })
```

### startRealtime (local only)

Streams data to a local callback only. There is no server connection.

```kotlin
fun startRealtime(type: Connections,
                  dataTypes: Set<DataTypes> = setOf(),
                  updateHandler: (Update) -> Unit)
```

### startRealtime (server only)

Streams data to Terra's WebSocket server only. There is no local callback.

{% hint style="warning" %}
The parameter order differs from the server + local overload: `token` is the second parameter here.
{% endhint %}

```kotlin
fun startRealtime(type: Connections,
                  token: String,
                  dataTypes: Set<DataTypes> = setOf(),
                  connectionCallback: (Boolean) -> Unit = { _ -> })
```

Parameters:

* `type` ➡ The connection type.
* `dataTypes` ➡ Set of data types to stream. Defaults to empty (streams all available).
* `token` ➡ The producer token for the WebSocket connection to Terra, minted from `POST /auth/user` (not the `initConnection` token). See [Authentication tokens](https://docs.tryterra.co/reference/streaming-api/api-endpoints.md).
* `updateHandler` ➡ Called with each `Update` data point.
* `connectionCallback` ➡ Called when the WebSocket connection state changes.

### stopRealtime

Stops streaming for a given connection type.

```kotlin
fun stopRealtime(type: Connections)
```

## Static methods

### setWebsocketEventListener

Sets a global listener for WebSocket connection events.

```kotlin
companion object {
    fun setWebsocketEventListener(listener: (Boolean, Error?) -> Unit)
}
```
