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
  • SDK Installation
  • Initialize the SDK
  • Connect to a data source
  • Validate the Connection
  • Disconnecting a user
  • Historical Data retrieval

Was this helpful?

  1. Health & Fitness API
  2. Mobile-Only Sources: Apple, Samsung, Google Fit

Android (Kotlin)

PreviousiOS (Swift)NextReact Native

Last updated 2 months ago

Was this helpful?

SDK Installation

Inside the dependencies section of your build.gradle file, add the following line of code

implementation 'co.tryterra:terra-android:{VERSION_NUMBER}'

You can find the latest version number on .

Sync your project with Gradle by clicking on the "Sync Project with Gradle Files" button in the toolbar. This will download the TerraAndroid SDK and make it available to your project.

Initialize the SDK

First, initialize the TerraManager class in the onCreate of your main activity

Terra initialization

Terra should be initialized every time your app is started

This is a necessary prerequisite for other SDK functions to run as expected

To do this, run the as below:

import co.tryterra.terra.Terra

class MainActivity : Activity() {
    private lateinit var terra: Terra

    public override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        var terra: TerraManager
        Terra.instance("YOUR DEV ID", "REFERENCE ID", this) { manager, error ->
            terra = manager
        }
    }
}

Connect to a data source

Once Terra is initialized, you can create a Samsung Health/Google Fit connection.

initConnection only needs to be run a single time.

Health Connect prohibits the permission popup to appear more than once for any given permission, so calling initConnection more than once will result in no action at all

The only case where it would re-appear is if:

  • you call initConnection with an expanded set of customPermissions

  • the app is deleted & reinstalled.

import co.tryterra.terra.Terra
import android.content.Context


class MainActivity : Activity() {
    private lateinit var terra: Terra

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

        // Example token received from your backend
        val token = "your_generated_token_from_backend"
        
        // The context is usually 'this' inside an Activity
        val context: Context = this

        // Define the custom permissions you want (optional, can be empty)
        val customPermissions: Set<CustomPermissions> = emptySet()

        // Whether the background scheduler is on
        val schedulerOn = true

        // Initialize the connection to Samsung Health
        terra.initConnection(
            connection = Connections.SAMSUNG,   // Connecting to Samsung Health
            token = token,                      // Token passed from backend
            context = context,                  // The activity context
            customPermissions = customPermissions,  // Custom permissions set
            schedulerOn = schedulerOn,          // Background scheduler on
            startIntent = null                  // Deprecated - always set to null
        ) { success, error ->
            if (success) {
                // Handle successful connection
                println("Connection to Samsung Health successful!")
            } else {
                // Handle connection failure
                error?.let {
                    println("Connection failed: ${it.message}")
                }
            }
        }
    }
}

customPermissions

customPermissions is used to customize the permissions list shown in the Apple Health popup when calling initConnection. When empty, it defaults to all available permissions

token

Validate the Connection

To ensure a connection is still valid on the client side, use the terra.getUserid() method. This function is synchronous and returns the user_id right away or null if none exists.

  • if the connection exists, all is good! 🎉 keep vibing along

Disconnecting a user

Historical Data retrieval

You may set toWebhook to false if you wish for the callback function to return the data payload on the client side.

val startDate = Date()  // Replace with your actual start date
val endDate = Date()    // Replace with your actual end date

terra.getDaily(
    type = Connections.APPLE_HEALTH,
    startDate = startDate,
    endDate = endDate,
    toWebhook = false  // Same as in Swift example
) { success, payload, error ->
    if (success) {
        payload?.let {
            println(it)  // If payload is non-null, print the data
        } ?: run {
            println("Failed to unpack payload")
        }
    } else {
        println("Get failed")
    }
}

Run the on the terra instance you created above to have the corresponding permission screen pop up.

Always use this method right after to see if the connection still exists,

if you expect the connection to exist, but returns null, to re-establish it. No permission screen will be shown again and the user flow will be unaffected

if it is expected for the connection to no longer exist, you may allow the user to re-connect if they so choose (you'd then call , but no permission screen would be shown)

In order to disconnect an SDK user, you may use , called from your backend

You can request for historical data using one of the .

Check out the for details about all the functions in the SDK

initializing Terra
Maven Central
call terra.initConnection
as before

SDK Installation

Requirements

  • Android 28 and above

Inside the dependencies section of your build.gradle file, add the following line of code

implementation 'co.tryterra:terra-android:{VERSION_NUMBER}'

Sync your project with Gradle by clicking on the "Sync Project with Gradle Files" button in the toolbar. This will download the TerraAndroid SDK and make it available to your project.

Health Connect Setup

In the Health Connect app:

Give all permissions between the app you wish to read from (e.g. Samsung Health/Google Fit & Health Connect.

In your AndroidManifest.xml

Include the following tags under the Activity you wish to link the user to when they click the privacy policy link in the Health Connect permission screen:

<intent-filter>
    <action android:name="androidx.health.ACTION_SHOW_PERMISSIONS_RATIONALE" />
</intent-filter>
<intent-filter>
  <action android:name="android.intent.action.VIEW_PERMISSION_USAGE"/>
  <category android:name="android.intent.category.HEALTH_PERMISSIONS"/>
</intent-filter>

Apply for Health Connect access

For each permission which you are not using, please add the following lines to your AndroidManifest.xml

<uses-permission android:name="android.permission.health.READ_HEART_RATE" tools:node="remove"/>

with android.permission.health.XXX for each permission you aren't using

installed on users' devices

You can find the latest version number on .

Before going LIVE (release), you will need to apply for permissions to access the Health Connect API with Google. Use this .

Health Connect
Maven Central
application form

If you do not need to access the , there is no reason to use Terra mobile SDKs!

If you need to access Terra's Health & Fitness API, it is only secure to do so from your server backend and send the desired data to your mobile frontend.

Never expose your API key on the client side unless you are simply testing

terra.initConnection
terra.getUserid()
terra.initConnection
the same endpoint as for Web API-based integrations
data retrieval functions
Kotlin SDK reference

token is a single-use token created to ensure the authentication endpoint for creating a (and connecting the SDK to Terra's servers) does not get abused.

In order to generate it, place the call below on your server, and provide it to your client side using your own logic.

Testing & developing

During the development phase, it it acceptable to place this call on the client side, exposing your API key in your mobile app.

For a production implementation, DO NOT expose your API key this way, and make sure to only make this call from your backend

Terra manager initialization function

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
}
mobile-only integrations