Terra Docs
Dashboard
  • Docs
  • API Reference
  • Changelog
  • Get started ⚡️ Choose your integration
  • Health & Fitness API
    • Overview
    • Set up your Integrations
    • Connect a User
    • Receive data updates
    • Request Historical data
    • Write data
    • Debugging FAQ
    • Mobile-Only Sources: Apple, Samsung, Google Fit
      • iOS (Swift)
      • Android (Kotlin)
      • React Native
      • Flutter
  • Streaming API
    • Getting Started
    • Wearable -> Your app
      • iOS (Swift)
      • Android
    • Your app -> Terra
      • iOS (Swift)
      • Android
    • Terra -> Your Backend
  • Teams API
  • Biomarkers API - Upcoming
Powered by GitBook
On this page

Was this helpful?

  1. Streaming API
  2. Wearable -> Your app

Android

PreviousiOS (Swift)NextYour app -> Terra

Last updated 2 months ago

Was this helpful?

Prerequisites

Ensure you have the following before you begin:

  1. Android Studio: The latest stable version.

  2. Terra Account: Access to your Terra Developer account and API key.

  3. Gradle Dependency: Ensure you include the TerraRT SDK in your project by adding the necessary dependencies.

    implementation 'co.tryterra:terra-rtandroid:X.X.X'

    based on

SDK Initialization

Always initialize the TerraRT class to begin using the SDK.

Do so every time the app is opened or brought into the foreground.

To do this, run the TerraRT manager initialization function as below:

import android.app.Activity
import android.content.Context
import com.terra.TerraRT

class MainActivity : Activity() {
    private lateinit var terraRT: TerraRT

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // Replace with your actual developer ID and reference ID
        val developerId = "yourDeveloperId"
        val referenceId: String? = "yourReferenceId"

        // Initialize TerraRT SDK
        terraRT = TerraRT(devId = developerId, context = this, referenceId = referenceId) { success ->
            if (success) {
                println("TerraRT initialized successfully")
                // Proceed with other setup tasks
            } else {
                println("Failed to initialize TerraRT")
                // Handle failure case
            }
        }
    }
}

Initializing a Connection

import com.terra.sdk.TerraRT

val terraRT = TerraRT()

val token = "yourAuthToken"  // Replace with your actual token

// Initialize TerraRT SDK connection
terraRT.initConnection(token) { success ->
    if (success) {
        println("TerraRT initialized successfully!")
    } else {
        println("Failed to initialize TerraRT.")
    }
}

To generate the token, make the below call from your backend

Device Connection Management

Once initialized, you can scan for devices and connect to them using the TerraRT SDK.

You can scan for devices using

  • BLE

  • ANT+ (if supported by the Android phone used)

Start Device Scan

You can choose whether to use cached devices (ones you've connected to before) or show a connection widget if no cached device is found.

// Start device scan
terraRT.startDeviceScan(type = Connections.BLE) { success ->
    if (success) {
        println("Device connected successfully!")
    } else {
        println("Failed to connect to the device.")
    }
}

Real-Time Data Streaming

Once the device is connected, you can start streaming real-time data such as heart rate, steps, and more.

Start Real-Time Streaming

import com.terra.sdk.DataTypes

val dataTypes: Set<DataTypes> = setOf(DataTypes.HEART_RATE, DataTypes.STEPS)

terraRT.startRealtime(type = Connections.BLE, dataTypes = dataTypes) { update ->
    handleUpdate(update)
}

Stop Real-Time Streaming

To stop real-time streaming for the connected device, use the following method:

kotlinCopy codeterraRT.stopRealtime(type = Connections.BLE)

This stops data streaming for the specified connection type.

Disconnect Device

To disconnect a connected device:

terraRT.disconnect(type = Connections.BLE)

This disconnects the BLE device or any specified connection type.

Example Usage

Full Example: Managing a BLE Connection and Streaming Data

kotlinCopy codeimport com.terra.sdk.TerraRT
import com.terra.sdk.Connections
import com.terra.sdk.DataTypes
import com.terra.sdk.Update

val terraRT = TerraRT()

val token = "yourAuthToken"  // Replace with your actual token

// Initialize TerraRT SDK connection
terraRT.initConnection(token) { success ->
    if (success) {
        println("TerraRT initialized successfully!")

        // Start device scan for BLE connection
        terraRT.startDeviceScan(type = Connections.BLE) { scanSuccess ->
            if (scanSuccess) {
                println("Device connected successfully!")

                // Start streaming real-time data
                val dataTypes: Set<DataTypes> = setOf(DataTypes.HEART_RATE, DataTypes.STEPS)
                terraRT.startRealtime(type = Connections.BLE, dataTypes = dataTypes) { update ->
                    handleUpdate(update)
                }

                // Stop streaming after 5 seconds for demo purposes
                android.os.Handler(Looper.getMainLooper()).postDelayed({
                    terraRT.stopRealtime(type = Connections.BLE)
                    println("Real-time streaming stopped.")

                    // Optionally disconnect the device
                    terraRT.disconnect(type = Connections.BLE)
                    println("Device disconnected.")
                }, 5000)
            } else {
                println("Failed to connect to the device.")
            }
        }
    } else {
        println("Failed to initialize TerraRT.")
    }
}

fun handleUpdate(update: Update) {
    println("Received update at timestamp: ${update.ts}")
    println("Update type: ${update.type}")
    update.val?.let { value ->
        println("Value: $value")
    }
}

Explanation:

  1. Initialization: The SDK is initialized using an authentication token.

  2. Device Connection: A BLE device is scanned and connected.

  3. Real-Time Streaming: Heart rate and steps data are streamed in real-time.

  4. Stop Streaming: After a delay of 5 seconds, the stream is stopped, and the device is disconnected.

Register the by calling .

This connects the to Terra, allows you to use other SDK functions, and allows it to be a once a is connected later on.

Use the and call initConnection as below using an authentication token.

You can start scanning for devices and allow the user to connect to a wearable device using .

Receiving a real time data stream depends on the being configured to broadcast the data it is collecting through BLE or ANT+

the latest version on maven central
terraRT instance created above

Generates an authentication token for the Terra mobile SDKs

post

Creates a token to be used with initConnection() functions in the Terra mobile SDKs in order to create a user record for Apple Health or Samsung Health (or equivalent)

Header parameters
dev-idstringRequired

your developer ID

Example: testingTerra
x-api-keystringRequired

your API key

Example: OtHJok60oQmT8zhnUWc4SWBJI7ztPTs88C0gOsJJ
Responses
200
200
application/json
404
404
application/json
post
POST /v2/auth/generateAuthToken HTTP/1.1
Host: api.tryterra.co
dev-id: text
x-api-key: text
Accept: */*
{
    "status": "success",
    "token": "250c68b9c21b78e40e7a3285a2d538d3bc24aabd3b4c76a782fb0a571ca4501d",
    "expires_in": 180
}
  • Prerequisites
  • SDK Initialization
  • Initializing a Connection
  • POSTGenerates an authentication token for the Terra mobile SDKs
  • Device Connection Management
  • Real-Time Data Streaming
  • Example Usage
phone
initConnection
phone
producer
device
startDeviceScan
device