> 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-migrating-to-2.md).

# Android upgrade guide

Move an Android app from terra-android 1.x to 2.x: the coordinate and package changes, the manifest, reference IDs, old calls mapped to new ones, and the Samsung Health setup.

`terra-android` 2.x is a rebuild, not an update. The Maven coordinate stays the same, but the Kotlin package, the entry point and every call changed. Plan it as a migration.

## Update the dependencies and imports

{% code title="app/build.gradle.kts" %}

```kotlin
dependencies {
    implementation("co.tryterra:terra-android:<VERSION>") // latest 2.x on Maven Central
}
```

{% endcode %}

If you used the 1.x Samsung-direct artifact `co.tryterra:android-sdk`, remove it. Samsung direct is now an add-on to `terra-android`: see [Update the Samsung Health setup](#update-the-samsung-health-setup) below.

Change every import from `co.tryterra.terra` to `co.tryterra.sdk`:

{% code title="YourApp.kt" %}

```kotlin
// 1.x
import co.tryterra.terra.Terra
import co.tryterra.terra.TerraManager
import co.tryterra.terra.enums.Connections

// 2.x
import co.tryterra.sdk.Terra
import co.tryterra.sdk.Source
import co.tryterra.sdk.EndUser
import co.tryterra.sdk.DataCategory
import co.tryterra.sdk.background.BackgroundSync
```

{% endcode %}

## Update the manifest

The 1.x AAR declared Health Connect permissions for you. The 2.x AAR declares none. Declare exactly the permissions for the categories you request, plus `READ_HEALTH_DATA_IN_BACKGROUND` and `READ_HEALTH_DATA_HISTORY` if you want background sync and more than 30 days of history. Also declare `INTERNET` and the Health Connect package query. See [Configure health permissions](https://docs.tryterra.co/mobile-sdks/android-sdk-2.md#configure-health-permissions).

Declare the privacy policy screen twice, for below and above Android 14. Without the Android 14 `activity-alias`, every read fails with "Incorrect health permission state".

## Move `reference_id` to your backend

In 1.x the app passed `referenceId` to `Terra.instance`. In 2.x your backend sets it when it mints the token. Use the same value 1.x used, so existing users keep their `user_id`:

{% code title="Your backend" %}

```bash
curl --request POST \
  --url 'https://api.tryterra.co/v2/auth/generateAuthToken?reference_id=<YOUR_USER_ID>' \
  --header 'dev-id: <YOUR_DEV_ID>' \
  --header 'x-api-key: <YOUR_API_KEY>'
```

{% endcode %}

The app still names the person, on every `connect`: [`terra.connect(Source.HEALTH, EndUser.Reference(user.id))`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#terra.connect), with the same value your backend puts in the token. The SDK restores a stored link only for the person it was made for. When someone else signs in on the same phone, it retires the old link and links again, so their data does not arrive under the previous person's `reference_id`. If your backend sends no `reference_id`, pass [`EndUser.Anonymous`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#enduser). Terra still trusts only the reference inside the token.

## Map the calls

| 1.x                                                                                                       | 2.x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| --------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Terra.instance(devId, referenceId, context) { manager, error -> }`                                       | [`Terra(context, devId = ..., tokenProvider = { ... })`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#terra.invoke). Synchronous. Build it once, in `Application.onCreate`                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `initConnection(Connections.HEALTH_CONNECT, token, context, customPermissions, schedulerOn, startIntent)` | [`terra.connect(Source.HEALTH, EndUser.Reference(user.id))`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#terra.connect), then [`terra.permissions.request(read = ..., launcher = launcher)`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#permissions.request)                                                                                                                                                                                                                                                                                                                                                                |
| `token` argument on `initConnection`                                                                      | The `tokenProvider` on `Terra(...)`, called only when a new link is needed. Or `terra.connect(Source.HEALTH, EndUser.Reference(user.id), token)` for a token already in hand                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `referenceId` argument on `Terra.instance`                                                                | `reference_id` on your backend's token request, and the [`EndUser`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#enduser) you pass to every `connect`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `customPermissions: Set<CustomPermissions>`                                                               | [`read: Set<DataCategory>`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#datacategory), for example `setOf(DataCategory.DAILY, DataCategory.SLEEP)`. In 2.3.0 and later, [`readTypes: Set<HealthDataType>`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#healthdatatype) asks for individual types, such as `setOf(HealthDataType.STEPS, HealthDataType.HEART_RATE)`. See [Request individual types](https://docs.tryterra.co/mobile-sdks/android-sdk-2.md#request-individual-types)                                                                                                                                           |
| `Connections.HEALTH_CONNECT`, `Connections.GOOGLE_FIT`                                                    | [`Source.HEALTH`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#source)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| `Connections.SAMSUNG`                                                                                     | `Source.HEALTH` reads everything in Health Connect, Samsung Health's data included. For Samsung's own store, `Source.SAMSUNG_HEALTH` with the add-on                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `getUserId(type)`                                                                                         | [`terra.connections()`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#terra.connections), and `userId` on what `connect` returns                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `checkAuth(...)`                                                                                          | [`terra.diagnostics.state()`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#diagnostics.state), which is `LinkRevoked` when Terra no longer accepts the device's link                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `allGivenPermissions(...)`                                                                                | [`terra.permissions.statuses()`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#permissions.statuses), or [`status(category)`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#permissions.status) for one                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `schedulerOn = true`, `enableBackgroundDelivery`, `isBackgroundDeliveryAvailable`                         | [`BackgroundSync.register(context, terra)`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#backgroundsync.register) in `Application.onCreate`, and [`terra.permissions.backgroundReadStatus()`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#permissions.backgroundreadstatus). Background read is asked for on the same sheet as everything else                                                                                                                                                                                                                                                                                |
| `getDaily`, `getBody`, ... with `toWebhook = true`                                                        | Removed from the device. [Historical data requests](https://docs.tryterra.co/unified-api/requesting-historical-data.md) from your backend with `to_webhook=true`. The device serves it on its next run                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| `getDaily` with `toWebhook = false`                                                                       | [`terra.daily.steps(range)`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#dailymetrics.steps). In 2.2.1 and later, also [`terra.daily.totals(range)`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#dailymetrics.totals) for each day's distance, active and basal energy and floors, [`terra.daily.intraday(range)`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#dailymetrics.intraday) for the records under those totals, and [`terra.body.restingHeartRate(range)`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#bodymetrics.restingheartrate) for resting heart rate, which needs `DAILY` |
| `getBody` with `toWebhook = false`                                                                        | [`terra.body.heartRate(range)`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#bodymetrics.heartrate). In 2.2.1 and later, also [`terra.body.readings(range)`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#bodymetrics.readings) for weight, height, body fat, lean mass, HRV, VO2 max, blood pressure, blood glucose, oxygen saturation, temperature and respiratory rate                                                                                                                                                                                                                                                      |
| `getSleep` with `toWebhook = false`                                                                       | [`terra.sleep.segments(range)`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#sleepmetrics.segments)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `getActivity` with `toWebhook = false`                                                                    | [`terra.activity.workouts(range)`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#activitymetrics.workouts). In 2.2.1 and later, each `Workout` also carries `title`, and [`terra.activity.routes(range)`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#activitymetrics.routes) and [`terra.activity.intensity(range)`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#activitymetrics.intensity) return GPS tracks and speed, power and cadence                                                                                                                                                                   |
| `getNutrition` with `toWebhook = false`                                                                   | 2.2.1 and later: [`terra.nutrition.quantities(range)`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#nutritionmetrics.quantities), one value per nutrient a meal recorded, and [`terra.nutrition.hydration(range)`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#nutritionmetrics.hydration) for water. Before 2.2.1 there is no local read: read nutrition from Terra's API or your webhook on your backend                                                                                                                                                                                                                    |
| `subscribe(...)` with `Terra.updateHandler`                                                               | [`terra.daily.changes()`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#dailymetrics.changes) and the other namespaces' `changes()`, which return a `Flow` of hints. Read the samples with the local reads                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `isHealthConnectAvailable(context)`                                                                       | 2.2.1 and later: [`terra.availability()`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#terra.availability), which needs no connection and returns `StoreAvailability.Available` or the reason, such as `ProviderAppMissing` or `ProviderAppTooOld`. Before 2.2.1 there is no separate call: `connect` and `permissions.request` throw [`TerraError.HealthDataUnavailable`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#terraerror) when Health Connect is missing or needs an update                                                                                                                                          |
| `openHealthConnect(context)`                                                                              | No equivalent                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| Disconnect through `deauthenticateUser` on your backend                                                   | Still works. On the device, [`terra.disconnect(Source.HEALTH)`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#terra.disconnect) also forgets the link and revokes its key                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |

Every call is a `suspend` function and throws a [`TerraError`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#terraerror). Each case has a stable `code` and an `isRetryable` answer.

### Before and after

{% tabs %}
{% tab title="1.x" %}
{% code title="YourApp.kt" %}

```kotlin
import co.tryterra.terra.Terra
import co.tryterra.terra.enums.Connections

Terra.instance("<DEV_ID>", "<USER_ID>", this) { manager, error ->
    if (manager.getUserId(Connections.HEALTH_CONNECT) == null) {
        manager.initConnection(
            connection = Connections.HEALTH_CONNECT,
            token = tokenFromBackend,
            context = this,
            customPermissions = setOf(),
            schedulerOn = true,
            startIntent = null,
        ) { success, error -> }
    }
}
```

{% endcode %}
{% endtab %}

{% tab title="2.x" %}
{% code title="YourApp.kt" %}

```kotlin
import co.tryterra.sdk.DataCategory
import co.tryterra.sdk.EndUser
import co.tryterra.sdk.Source
import co.tryterra.sdk.Terra
import co.tryterra.sdk.background.BackgroundSync

// Application.onCreate
terra = Terra(this, devId = "<DEV_ID>", tokenProvider = { backend.mintTerraToken() })
BackgroundSync.register(this, terra)

// Activity.onCreate, before anything suspends
launcher = terra.permissions.launcher(this)

// On tap
terra.connect(Source.HEALTH, EndUser.Reference(user.id))
terra.permissions.request(
    read = setOf(DataCategory.DAILY, DataCategory.SLEEP, DataCategory.ACTIVITY),
    launcher = launcher,
)
```

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

## Update the Samsung Health setup

In 1.x, Samsung Health came two ways: `Connections.SAMSUNG` in `terra-android`, which read Samsung Health's data out of Health Connect, and the separate `co.tryterra:android-sdk` artifact, which read Samsung's store directly.

In 2.x:

* **Through Health Connect**, connect `Source.HEALTH`. There is no Samsung-only filter: Health Connect's data from every app is uploaded.
* **Directly**, add `co.tryterra:terra-android-samsung` (the same version as `terra-android`) and register it with [`samsungHealth()`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#samsunghealth).

Two things change for the direct route:

* **You download Samsung's SDK yourself.** Samsung's licence forbids redistributing its Health Data SDK. You download version 1.1.0 from Samsung and package it in your app.
* **Your app needs its own Samsung approval.** Samsung approves each package name and signing certificate separately. Register yours with Samsung, and use Samsung Health's developer mode until it is approved.

See [Samsung Health](https://docs.tryterra.co/mobile-sdks/samsung-health.md) for the setup, and for how the two stores avoid sending a record twice.

{% 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 %}
