> 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/mobile-sdks/android-kotlin.md). Agents can also search and read this documentation through its [MCP server](https://docs.tryterra.co/~gitbook/mcp).

# Android SDK 1.x

Connect Samsung Health and Health Connect users with the terra-android 1.x SDK: install it, initialise it, connect a user and enable background delivery.

This page shows how to integrate Android health stores in your Android app with `terra-android` 1.x. It covers SDK initialization, user connection, permission handling and background data updates.

{% hint style="info" %}
`terra-android` 1.x is no longer the current version. For new apps, use the [Android SDK](https://docs.tryterra.co/mobile-sdks/android-sdk-2.md) (2.x). To move an existing app, follow [Android upgrade guide](https://docs.tryterra.co/mobile-sdks/android-migrating-to-2.md).
{% endhint %}

The TerraAndroid SDK supports the following integrations:

* Samsung Health
* Health Connect

## Install the SDK

### Add Terra to `build.gradle`

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

<pre class="language-gradle" data-title="build.gradle"><code class="lang-gradle"><strong>implementation 'co.tryterra:terra-android:{VERSION_NUMBER}'
</strong></code></pre>

* You can find the latest version number on [Maven Central](https://central.sonatype.com/artifact/co.tryterra/terra-android/).

### Sync your project with `build.gradle`

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

{% hint style="info" %}
**Requirements**

* Your app build config must be for **Android 28 (minSDK 28)** and above.
* The device must have the required app installed, e.g. Health Connect or Samsung Health
  {% endhint %}

### Configure health permissions

{% tabs %}
{% tab title="Apply to use Samsung Health" %}
Terra has a privileged partnership with Samsung that gives you direct access to the Samsung Health SDK, with no Health Connect intermediary. This is the recommended route for Samsung devices.

**1. Apply for Samsung Health access**

Submit your application through the [Samsung Health partnership portal](https://developer.samsung.com/SHealth/business-partner/m48wvqi1mt9w2w4c).

{% hint style="info" %}
While waiting for approval, you can start development immediately using the **Health Connect** route (see the other tab). Switching to Samsung direct later only changes the dependency you pull. No code changes are needed.
{% endhint %}

**2. Install the Samsung-direct SDK**

After approval, replace `co.tryterra:terra-android` with the separate Samsung-direct artifact:

```gradle
implementation 'co.tryterra:android-sdk:{VERSION_NUMBER}'
```

Find the latest version on [Maven Central](https://central.sonatype.com/artifact/co.tryterra/android-sdk). Note that this is a separate artifact, not a tagged version of `terra-android`. Your `initConnection(Connections.SAMSUNG, ...)` call and the rest of your code stay exactly the same.

**3. Add ProGuard rule (required for release builds)**

Add this to your `proguard-rules.pro`:

```proguard
-keep class com.samsung.android.** { *; }
```

Without this, R8 minification will strip Samsung SDK classes and cause runtime crashes in production.

**4. Requirements**

* **Samsung Health** app must be installed on the device
* **Android 28 (minSDK 28)** and above
* Enable **Developer Mode** in Samsung Health on test devices (Settings > About Samsung Health > tap version number repeatedly)
* No additional manifest or Gradle changes are needed: the Terra SDK handles everything
  {% endtab %}

{% tab title="Apply to use Health Connect" %}
**1. In the Health Connect app**

Give all permissions between the apps you wish to read from (e.g. **Samsung Health, Google Fit, etc**) & Health Connect.

**2. Add Health Connect capability to your app**

Include the permission tags under the Activity you wish to link the user to when they click the **privacy policy** link in the Health Connect permission screen. Here are the steps:

1. Go to your Android App's `AndroidManifest.xml`
2. Go to your privacy policy `<activity>` and include the following tags under this `<activity>` tag.

"Your Android manifest needs to have an Activity that displays your app's **privacy policy**, which is your app's rationale of the requested permissions, describing how the user's data is used and handled." (Health Connect)

<pre class="language-xml" data-title="AndroidManifest.xml" data-line-numbers><code class="lang-xml"><strong>&#x3C;intent-filter>
</strong>  &#x3C;action android:name="androidx.health.ACTION_SHOW_PERMISSIONS_RATIONALE" />
 &#x3C;/intent-filter>
  
&#x3C;intent-filter>
   &#x3C;action android:name="android.intent.action.VIEW_PERMISSION_USAGE"/>
  &#x3C;category android:name="android.intent.category.HEALTH_PERMISSIONS"/>
&#x3C;/intent-filter>
</code></pre>

{% hint style="warning" %}
**Apply for Health Connect access**

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

1. Use this [application form](https://developer.android.com/health-and-fitness/guides/health-connect/publish/declare-access#explain-use-data-types).
2. For each permission which you are not using, please add the following lines to your AndroidManifest.xml

```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
{% endhint %}
{% endtab %}
{% endtabs %}

## Initialize the SDK

The initialization only needs to be done once on app start (for example in your `MainActivity` file or equivalent), and every time the app is brought into the foreground. This ensures that the SDK is properly set up and ready to be used.

{% hint style="warning" %}
The SDK should be initialized every time your app is started.

This is a necessary prerequisite for other SDK functions to run as expected
{% endhint %}

### Import `Terra` and `TerraManager`

In your Android Studio project, you should now be able to import classes from the Terra SDK.

{% code title="MainActivity.kt" lineNumbers="true" %}

```kotlin
import co.tryterra.terra.Terra
import co.tryterra.terra.TerraManager
```

{% endcode %}

### Get a `TerraManager` instance

To do this, run the [Terra manager initialization function](https://docs.tryterra.co/reference/mobile-sdks/android-kotlin#instance) as below:

{% code title="MainActivity.kt" lineNumbers="true" %}

```kotlin
import co.tryterra.terra.Terra
import co.tryterra.terra.TerraManager

import java.lang.IllegalStateException

class MainActivity : AppCompatActivity() {
    private lateinit var terra: TerraManager

    public override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        Terra.instance("YOUR DEV ID", "REFERENCE ID", this) { manager, error ->
            error?.let {
                throw IllegalStateException("🤯: Error initialising terra ${it.message}")
            }
            terra = manager
        }
    }
}
```

{% endcode %}

This call is asynchronous. Make sure it completes before you use the manager.

## Connect a user

Once Terra is initialized, you can create a connection (e.g. Samsung Health or Health Connect).

Call [`terra.initConnection`](https://docs.tryterra.co/reference/mobile-sdks/android-kotlin#initconnection) from the `TerraManager` instance you've created above to have the corresponding permission screen pop up.

### Call `initConnection()`

This method triggers a permission popup and establishes the connection.

From the `TerraManager` instance, call [`initConnection()`](https://docs.tryterra.co/reference/mobile-sdks/android-kotlin#initconnection) with the following arguments:

* `type`: Specify the connection type: `Connections.SAMSUNG` for Samsung Health or `Connections.HEALTH_CONNECT` for Health Connect
* `token`: A **one-time authentication token** generated from your **backend server** using Terra API. This ensures secure communication between your app and the Terra servers.
* `customPermissions`: A **set of permissions** that define what data you want to request (e.g., heart rate, steps). If empty, it defaults to all available permissions. See [Permissions mapping](https://docs.tryterra.co/reference/mobile-sdks/permissions-mapping) for every value and the Health Connect (or Samsung) data type it requests.
* `schedulerOn`: Enables background delivery, so Terra keeps syncing while your app is in the background. Defaults to `true`. On Health Connect connections, Terra also requests Health Connect's background-read permission as part of this flow. See [Set up background delivery](#set-up-background-delivery) below.

To learn more about these parameters and their different options, check the [Android SDK Reference.](https://docs.tryterra.co/reference/mobile-sdks/android-kotlin)

{% tabs %}
{% tab title="Samsung Health" %}
{% code title="MainActivity.kt" lineNumbers="true" %}

```kotlin
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log

import co.tryterra.terra.Terra
import co.tryterra.terra.TerraManager
import co.tryterra.terra.enums.Connections

import java.lang.IllegalStateException

class MainActivity : AppCompatActivity() {
    private lateinit var terra: TerraManager

    override fun onCreate(savedInstanceState: Bundle?) {
        // Create the Terra Manager as shown in Get a TerraManager instance
    }

    fun initialiseUserConnection() {
        if (!this::terra.isInitialized){
            throw IllegalStateException("🤯: Terra Manager not initialised yet")
        }
        val token = "your_generated_token_from_backend"

        terra.initConnection(
            connection = Connections.SAMSUNG,
            token = token,
            context = this,
            customPermissions = setOf(),
            schedulerOn = true,
            startIntent = null
        ) { success, error ->
            error?.let {
                throw IllegalStateException("🤯: ${it.message}")
            }
            Log.i("MainActivity", "Auth Success status: $success")
        }
    }
}
```

{% endcode %}
{% endtab %}

{% tab title="Health Connect" %}
{% code title="MainActivity.kt" lineNumbers="true" %}

```kotlin
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log

import co.tryterra.terra.Terra
import co.tryterra.terra.TerraManager
import co.tryterra.terra.enums.Connections

import java.lang.IllegalStateException

class MainActivity : AppCompatActivity() {
    private lateinit var terra: TerraManager

    override fun onCreate(savedInstanceState: Bundle?) {
        // Create the Terra Manager as shown in Get a TerraManager instance
    }

    fun initialiseUserConnection() {
        if (!this::terra.isInitialized){
            throw IllegalStateException("🤯: Terra Manager not initialised yet")
        }
        val token = "your_generated_token_from_backend"

        terra.initConnection(
            connection = Connections.HEALTH_CONNECT,
            token = token,
            context = this,
            customPermissions = setOf(),
            schedulerOn = true,
            startIntent = null
        ) { success, error ->
            error?.let {
                throw IllegalStateException("🤯: ${it.message}")
            }
            Log.i("MainActivity", "Auth Success status: $success")
        }
    }
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

{% hint style="info" %}
**`initConnection` only needs to be called 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 and reinstalled
* the app requested a permission that Google did not grant for release
  {% endhint %}

#### Generate an auth token

To be able to call the `initConnection()` method, you need to pass a `token` as an argument.

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

Generate the token with this endpoint <mark style="color:orange;">`POST`</mark>`https://api.tryterra.co/v2/auth/generateAuthToken` . Make sure to call it with your Terra `x-api-key` and `dev-id` in the headers from **your backend server.** After you generate the token, provide the response to your client side using your own logic.

{% code title="CLI" %}

```bash
curl --request POST \
  --url https://api.tryterra.co/v2/auth/generateAuthToken \
  --header 'dev-id: <YOUR-DEV-ID>' \
  --header 'x-api-key: <YOUR-API-KEY>'
```

{% endcode %}

For every parameter, see the [`/auth/generateAuthToken` endpoint](https://docs.tryterra.co/reference/health-and-fitness-api/authentication#post-auth-generateauthtoken) in the API reference.

{% hint style="warning" %}

* 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.**
  {% endhint %}

## Validate the connection

To ensure a connection is still valid on the client side, use the [`terra.getUserId()`](https://docs.tryterra.co/reference/mobile-sdks/android-kotlin#getuserid) method. This function is synchronous and returns the `user_id` right away or null if none exists.

{% hint style="info" %}
**Always validate the connection before using the SDK**

Check if a `user_id` exists right after **initializing the Terra SDK** to see if the connection still exists.

1. **Check if the User is Connected**
   1. If the function returns a user ID, the user is still connected, 🎉 keep vibing along!
   2. If the function returns <mark style="color:red;">`nil`</mark>, the user needs to reconnect.
2. **Re-connect if Needed**\
   If the connection is lost, you can call `terra.initConnection()` again to re-establish the connection.

Calling `terra.initConnection()` when the user is already connected or just needs a reconnection will re-establish the connection if necessary, and the user flow will remain uninterrupted.

On Apple Health, note that a `user_id` only tells you the connection exists on our side, not that your app still holds HealthKit access. Deleting an app clears its HealthKit authorization while the Terra connection survives, so the permission screen can still appear on the next `initConnection()` if iOS has not yet determined permissions for the current install.
{% endhint %}

## Set up background delivery

Background delivery keeps Health Connect data syncing while your app is in the background, rather than only while it is open. It requires `terra-android` **1.7.0 or later**, and we recommend **1.7.3 or later**. Before that, the periodic sync could be scheduled even when the user had not granted the background-read permission, so it ran without being able to read.

Passing `schedulerOn = true` to `initConnection` (the default) is all that is needed. Terra requests Health Connect's background-read permission during the connection flow and schedules the periodic sync as soon as the user grants it.

{% hint style="info" %}
If you use the Samsung-direct `co.tryterra:android-sdk` artifact described in [Install the SDK](#install-the-sdk), it is on a separate version line and does not go through Health Connect. Check with support before relying on background delivery there.
{% endhint %}

If the user declines that permission, background sync is not scheduled. Call `enableBackgroundDelivery` to prompt again:

{% code title="MainActivity.kt" lineNumbers="true" %}

```kotlin
terra.enableBackgroundDelivery { success, error ->
    if (success) {
        Log.i("MainActivity", "Background delivery enabled")
    } else {
        Log.w("MainActivity", "Background delivery unavailable: ${error?.message}")
    }
}
```

{% endcode %}

To read the current state without prompting the user, call `isBackgroundDeliveryAvailable` (available from `terra-android` 1.7.3):

{% code title="MainActivity.kt" lineNumbers="true" %}

```kotlin
terra.isBackgroundDeliveryAvailable { granted ->
    Log.i("MainActivity", "Background read granted: $granted")
}
```

{% endcode %}

It returns `false` if called before `initConnection`, which is indistinguishable from the user having declined. Call it only once a connection exists.

{% hint style="info" %}
`enableBackgroundDelivery` reports failure through its `TerraError`:

* `BackgroundDeliveryPermissionDenied`: the user declined the prompt.
* `BackgroundDeliveryNotSupported`: the Health Connect SDK is not available on the device.
* `NotAuthenticated`: called before `initConnection`.
* `UnexpectedError`: the context you passed to Terra does not extend `AppCompatActivity`, so the permission request cannot be launched.
  {% endhint %}

You now receive health data events automatically at your destination (for example, a webhook).

You can also request historical data to backfill, to verify that data exists, or as a fallback.

Check out the [Android SDK reference](https://docs.tryterra.co/reference/mobile-sdks/android-kotlin) for details about all the functions in the SDK.

## Example app

{% code title="MainActivity.kt" lineNumbers="true" %}

```kotlin
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log

import co.tryterra.terra.Terra
import co.tryterra.terra.TerraManager
import co.tryterra.terra.enums.Connections

import java.lang.IllegalStateException

class MainActivity : AppCompatActivity() {
    private lateinit var terra: TerraManager

    public override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        Terra.instance("YOUR DEV ID", "REFERENCE ID", this) { manager, error ->
            error?.let{it -> 
                throw IllegalStateException("🤯: Error initialising terra ${it.message}")
            }
            terra = manager
            this.initialiseUserConnection()
        }
    }

    fun initialiseUserConnection() {
        if (!this::terra.isInitialized){
            throw IllegalStateException("🤯: Terra Manager not initialised yet")
        }
        
        if (terra.getUserId(Connections.SAMSUNG) != null){
            // User already connected
            return
        }
        
        // Initialize the connection to Samsung Health
        terra.initConnection(
            connection = Connections.SAMSUNG,   // Connecting to Samsung Health
            token = "AUTH TOKEN",                      // Token passed from backend
            context = this,                  // The activity context
            customPermissions = setOf(),  // Custom permissions set (empty set defaults to all permissions)
            schedulerOn = true,                 // Background scheduler on
            startIntent = null                  // Deprecated - always set to null
        ) { success, error ->
            error?.let {
                throw IllegalStateException("🤯: ${it.message}")
            }
            // Connection successful!
            Log.i("MainActivity", "Auth Success status: $success")
        }
    }
}
```

{% endcode %}

## Disconnect a user

In order to disconnect an SDK user, you may use [the same endpoint as for Web API-based integrations](https://docs.tryterra.co/reference/health-and-fitness-api/authentication#delete-auth-deauthenticateuser), called from your backend.

## Request historical data

You can request for historical data using one of the [data retrieval functions](https://docs.tryterra.co/reference/mobile-sdks/android-kotlin#data-retrieval).

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

{% code title="MainActivity.kt" lineNumbers="true" %}

```kotlin
import co.tryterra.terra.enums.Connections
import java.time.Instant
import java.time.temporal.ChronoUnit
import java.util.*

fun requestData() {
    val startDate = Date.from(Instant.now().minus(1, ChronoUnit.DAYS))
    val endDate = Date()

    // Request for yesterday and today's data
    terra.getDaily(
        type = Connections.SAMSUNG,
        startDate = startDate,
        endDate = endDate,
        toWebhook = false 
    ) { success, payload, error ->
        error?.let{
            throw IllegalStateException("🤯: Error requesting data ${it.message}")    
        }
        // Process payload here
    }
}
```

{% endcode %}

{% hint style="info" %}
**The mobile SDKs are only for Apple Health, Health Connect and Samsung Health.** These have no web API, so your app reads them on the phone and sends the data to Terra. Every other provider connects through the [Unified API](https://docs.tryterra.co/unified-api/getting-started) with no SDK.
{% endhint %}
