> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hightouch.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Android SDK

> Hightouch's Android SDK for collecting events

The Android SDK makes it easy to track events from Java and Kotlin Android applications.

## Installation

The Android SDK is published to [Maven Central](https://central.sonatype.com/artifact/com.hightouch.analytics.android/analytics).

Install it through Gradle. Include `mavenCentral()` in your dependency repositories:

```text theme={null}
// settings.gradle
dependencyResolutionManagement {
  repositories {
    google()
    mavenCentral()
  }
}
```

Replace `HIGHTOUCH_VERSION` with the released SDK version you want to use:

```text theme={null}
// app/build.gradle

dependencies {
  implementation 'com.hightouch.analytics.android:analytics:HIGHTOUCH_VERSION'
}
```

Existing JitPack installations can switch to these Maven Central coordinates. Remove the old `com.github.ht-sdks.events-sdk-android` dependency when switching to avoid including the core SDK twice.

## Initialization

You should initialize the SDK in a central location and store it in a variable
for use across your application. For example, you may want to initialize it in
your application's `onCreate` callback. After initialization, you can use the
SDK anywhere you import the `Analytics` class via the singleton instance.

**Kotlin example**:

```
import com.hightouch.analytics.Analytics

val analytics = Analytics.Builder(context, "YOUR_WRITE_KEY")
    .defaultApiHost("us-east-1.hightouch-events.com/v1")
    .trackApplicationLifecycleEvents()
    .build()

Analytics.setSingletonInstance(analytics)
```

**Java example**:

```
import com.hightouch.analytics.Analytics

Analytics analytics = new Analytics.Builder(context, "YOUR_WRITE_KEY")
    .defaultApiHost("us-east-1.hightouch-events.com/v1")
    .trackApplicationLifecycleEvents()
    .build();

Analytics.setSingletonInstance(analytics);
```

**Configuration options**:

| Option | Type | Description |
| - | - | - |
| `defaultApiHost` | String | The API host to send the tracked events to. |
| `flushQueueSize` | int | The number of events to queue before sending events to the Hightouch API. Defaults to 20. |
| `flushInterval` | int | The maximum amount of time (in seconds) to store events locally before forwarding to Hightouch. Defaults to 30 seconds. |
| `trackApplicationLifecycleEvents` | n/a | Automatically track application lifecycle events (like opening the application). |
| `recordScreenViews` | n/a | Automatically track screen views. |
| `trackDeepLinks` | n/a | Automatically track deep links. |
| `foregroundSessionTimeout` | long | Maximum foreground inactivity in milliseconds before a new session starts. Defaults to `1800000` (30 minutes). |
| `backgroundSessionTimeout` | long | Maximum time in the background, in milliseconds, before a new session starts on resume. Defaults to `1800000` (30 minutes). |

### Context

By default, Hightouch automatically collects contextual metadata with each event, such as the device operating system. This context is forwarded with each event.

#### Modify global context

To customize the default context sent with every event, use the `getAnalyticsContext()` method. This allows you to add or remove metadata that will be included with all subsequent events.

For example, to set UTM campaign parameters globally:

```
AnalyticsContext context = Analytics.with(context).getAnalyticsContext();
context.putValue("custom_key", "custom_value");
```

This applies the campaign data to every future event in the session.

For more information, see:

* [AnalyticsContext.java](https://github.com/ht-sdks/events-sdk-android/blob/main/analytics/src/main/java/com/hightouch/analytics/AnalyticsContext.java)
* [Android SDK README – Context](https://github.com/ht-sdks/events-sdk-android#context)

#### Override context per event

You can override the context for an individual `track()` or `identify()` call by passing an `Options` object as the third argument. This is useful when you want to apply custom context — like UTM campaign parameters — to a single event.

```
ValueMap campaign = new ValueMap()
    .putValue("utm_source", "adwords")
    .putValue("utm_medium", "cpc")
    .putValue("utm_campaign", "product_launch");

ValueMap contextMap = new ValueMap().putValue("campaign", campaign);

Options options = new Options().setContext(contextMap);

Analytics.with(context).track("Product Viewed", null, options);
```

This will attach campaign context only to the specified event.

For implementation details, see:

* [Options.java](https://github.com/ht-sdks/events-sdk-android/blob/main/analytics/src/main/java/com/hightouch/analytics/Options.java)
* [Android SDK README – Context](https://github.com/ht-sdks/events-sdk-android#context)

## Prebuilt plugins

Use Hightouch's prebuilt plugins to add integrations without writing a plugin yourself. Optional plugins can require an additional artifact or destination SDK.

### Braze

Use the Braze plugin to forward Hightouch calls to the Braze SDK on the device. This lets Braze evaluate in-app message triggers while the user is active, alongside normal event collection in Hightouch.

Add the plugin and Braze SDK to your app's Gradle dependencies. Replace `HIGHTOUCH_VERSION` with `0.2.0` or later, using the same version for the plugin and your core Hightouch dependency:

```text theme={null}
implementation 'com.hightouch.analytics.android:analytics-braze:HIGHTOUCH_VERSION'
implementation 'com.braze:android-sdk-base:41.1.1'
```

The plugin does not bundle the Braze SDK. The example uses Braze 41.1.1, which requires Android API 29 or later. Use `android-sdk-ui` instead of `android-sdk-base` if your app needs Braze's default UI.

In your application's `onCreate`, register the integration when building your Hightouch client. Use your Braze SDK API key and SDK endpoint:

```kotlin theme={null}
import com.hightouch.analytics.Analytics
import com.hightouch.analytics.braze.BrazeIntegration

val brazeFactory = BrazeIntegration.builder(
    context, "YOUR_BRAZE_SDK_API_KEY", "YOUR_BRAZE_SDK_ENDPOINT"
)
    .forwardScreenViews(true)
    .build()

val analytics = Analytics.Builder(context, "YOUR_WRITE_KEY")
    .defaultApiHost("us-east-1.hightouch-events.com/v1")
    .use(brazeFactory)
    .build()
```

The plugin forwards `identify` calls as user updates and `track` calls as custom events. By default, `Order Completed` and `Completed Order` become purchases, with one purchase per product. Screen forwarding is off by default; `.forwardScreenViews(true)` forwards `screen` calls as custom events.

Your application configures message presentation, Content Cards, and push notifications. The API-key setup above manages Braze sessions. If you supply an existing instance through `BrazeIntegration.builder(context, existingBraze)`, your application manages its sessions.

See the [Braze sample](https://github.com/ht-sdks/events-sdk-android/tree/main/analytics-samples/braze-sample) for application and UI setup. If you're replacing an mParticle kit, follow Migrate the mParticle Braze kit.

## Session tracking

Session tracking is enabled by default. The SDK attaches `sessionId`, `sessionStart`, and a `session` object to `context` on every event so you can group events from the same app session.

Sessions use two timeouts, both in milliseconds:

* `foregroundSessionTimeout` limits inactivity while the app is in the foreground.
* `backgroundSessionTimeout` limits how long the app can stay in the background before the next resume starts a new session.

Both default to `1800000` (30 minutes). Set both to `0` to disable session tracking.

A new session starts when any of these occur:

* First launch, when no session state is persisted.
* Foreground inactivity exceeds `foregroundSessionTimeout`.
* Resume after being backgrounded longer than `backgroundSessionTimeout`, including after process death.
* Calling `reset()`.

Session state is persisted across app relaunches. `sessionIndex` is a per-device lifetime counter. It starts at `0` and resets only when the app is uninstalled, not when you call `reset()`.

You can change the timeouts when you initialize the SDK:

**Kotlin example**:

```
val analytics = Analytics.Builder(context, "YOUR_WRITE_KEY")
    .foregroundSessionTimeout(60 * 60 * 1000)
    .backgroundSessionTimeout(60 * 60 * 1000)
    .build()
```

**Java example**:

```
Analytics analytics = new Analytics.Builder(context, "YOUR_WRITE_KEY")
    .foregroundSessionTimeout(60 * 60 * 1000)
    .backgroundSessionTimeout(60 * 60 * 1000)
    .build();
```

`context.session` includes:

| Field | Type | Description |
| - | - | - |
| `sessionId` | int | Current session ID (epoch milliseconds). |
| `sessionIndex` | int | Per-device lifetime counter. Starts at `0`. |
| `sessionStart` | boolean | Present and `true` only on the first event of the session. |
| `eventIndex` | int | 0-based index of the event within the session. |
| `previousSessionId` | int or null | Previous session ID. `null` on the first session. |
| `firstEventId` | UUID | `messageId` of the session's first event. |
| `firstEventTimestamp` | ISO 8601 | When the session began. |

`sessionId` and `sessionStart` are also set on `context` for parity with the [browser SDK](https://docs.hightouch.com/events/sdks/browser.md#session-tracking). `sessionStart` is included only when it is `true`.

## API

### Identify

The `identify` method sends an `identify` event. It accepts user id and trait
information for the current user -- if you only have partial information, you
can just supply a single parameter.

**Java method signature**:

```
Analytics.with(context).identify("userId", new Traits().putEmail("email"), null);
```

**Kotlin method signature**:

```
Analytics.with(context).identify("userId", Traits().putEmail("email"), null);
```

**Method parameters**:

| Parameter | Type | Description |
| - | - | - |
| `userId` | String | The user's persistent ID |
| `traits` | Traits (optional) | Additional traits about the user, such as `email` and `name`. |
| `options` | Options (optional) | Overrides to the event's context may be passed through the `options` object. This includes setting custom fields like [campaign data](#override-context-per-event). *Note that this overrides the default context.* |

### Track

The `track` method sends a `track` event. The event name is required, and
additional properties that describe the event may be supplied.

**Java method signature**:

```
Analytics.with(context).track("eventName", new Properties().putValue("custom", "property"), null);
```

**Kotlin method signature**:

```
Analytics.with(context).track("eventName", Properties().putValue("custom", "property"), null);
```

**Method parameters**:

| Parameter | Type | Description |
| - | - | - |
| `name` | String | The name of the event. |
| `properties` | Properties (optional) | Additional properties about the event, such as `product_id`. |
| `options` | Options (optional) | Overrides to the event's context may be passed through the `options` object. Note that this overrides the default context. |

### Screen

The `screen` method sends a `screen` event. The screen title is required, and
additional information about the screen's category and properties may be
supplied.

**Java method signature**:

```
Analytics.with(context).screen("category", "name", new Properties().putValue("custom", "property"), null);
```

**Kotlin method signature**:

```
Analytics.with(context).screen("category", "name", Properties().putValue("custom", "property"), null);
```

**Method parameters**:

| Parameter | Type | Description |
| - | - | - |
| `category` | String (optional if name is supplied) | The screen's category. For example "Docs" |
| `title` | String (optional if category is supplied) | The screen's name. For example "Getting started" |
| `properties` | Properties (optional) | Additional properties about the event, such as `from_link`. |
| `options` | Options (optional) | Overrides to the event's context may be passed through the `options` object. Note that this overrides the default context. |

### Group

The `group` method sends a `group` event.

The id identifying the user's group is required. Additional traits on the group
can be provided.

**Java method signature**:

```
Analytics.with(context).group("groupId", new Traits().putValue("custom", "property"), null);
```

**Kotlin method signature**:

```
Analytics.with(context).group("groupId", Traits().putValue("custom", "property"), null);
```

**Method parameters**:

| Parameter | Type | Description |
| - | - | - |
| `groupId` | String | The id for the group. |
| `traits` | Traits (optional) | Additional traits about the group, such as `company_name`. |
| `options` | Options (optional) | Overrides to the event's context may be passed through the `options` object. Note that this overrides the default context. |

### Flush

The Android SDK buffers events locally before sending them to Hightouch's servers.
This minimizes the number of requests made by the SDK and makes the tracking
non-blocking.

To force the local buffer to be sent to Hightouch immediately call the `flush`
method.

**Method signature**:

```
Analytics.with(context).flush()
```

### Reset

The `reset` method resets the `identify` and `group` for the local session.

The `reset` method should be called when users log out. This way, if the user
logs back in with another account, the userIds and traits from the different
sessions remain separate. Calling `reset()` also starts a new analytics session.
See [Session tracking](#session-tracking).

**Method signature**:

```
Analytics.with(context).reset()
```

### Opt out

The `optOut` method disabled event tracking. When called, events are not sent
to Hightouch's servers.

Note that the opt out persists across device reboots. To opt back in to
tracking, pass `false` to `optOut`.

**Method signature**:

```
Analytics.with(context).optOut(true)
```
