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

# Android SDK

> Send events from your Android app to Tranthor, and register it for push

The Tranthor Android SDK is a Kotlin library. It sends `identify`, `track`, `page` and `screen` events from your app, keeps them on disk until they are delivered, and, with its optional push module, registers the phone for [mobile push](https://docs.tranthor.com/integrations/channels/mobile-push.md).

It needs Android 6.0 (API 23) or later.

## Installation

The SDK has two modules:

| Module | What it does |
| - | - |
| `tranthor-sdk` | Events, identity and consent. Always needed. Adds only the `INTERNET` permission. |
| `tranthor-push` | Registers the phone for push through Firebase Cloud Messaging and reports what happens to each push. Adds the `POST_NOTIFICATIONS` permission. |

> [!NOTE]
>
> The Android SDK artifacts are not on Maven yet. Contact us at [support@tranthor.com](mailto:support@tranthor.com) for the build to add to your project.

## Usage

```kotlin theme={null}
import com.tranthor.sdk.Configuration
import com.tranthor.sdk.TranthorSDK
import com.tranthor.sdk.jsonObjectOf

// The write key identifies your workspace. Find it in Tranthor under Settings.
// Pass the complete value, for example "Basic trn_abcdefg...".
val sdk = TranthorSDK.configure(applicationContext, Configuration(writeKey = "Basic trn_abcdefg..."))

// Tie the customer to their actions and record traits about them.
sdk.identify(userId = "user-123", traits = jsonObjectOf("email" to "alex@example.com", "plan" to "trial"))

// Record an action, with any properties that describe it.
sdk.track("Completed Order", properties = jsonObjectOf("orderId" to "ORD-789", "revenue" to 99.99))

// Record a screen the customer saw.
sdk.screen("Product Page", properties = jsonObjectOf("category" to "Electronics"))

// Wait until everything queued has been sent.
sdk.flush()
```

These are `suspend` functions, so call them from a coroutine. Create one instance, for example in your `Application`, and keep it for the life of the app. Each call returns once the event is saved on the phone. It does not wait for the network, so events survive the app being closed.

### From Java

Java code uses `TranthorClient`, which takes callbacks and keeps calls in the order you make them:

```java theme={null}
Configuration configuration = new Configuration.Builder("Basic trn_abcdefg...").build();
TranthorClient.configure(context, configuration, (client, error) -> {
    if (client == null) return;
    client.track("Completed Order", Collections.singletonMap("orderId", "ORD-789"));
    client.flush((unit, flushError) -> { /* flushError is null on success */ });
});
```

## Methods

| Method | What it does |
| - | - |
| `identify(userId, traits)` | Records traits and stores the user id for later events. |
| `track(event, properties)` | Records an event. |
| `page(name, properties)` and `screen(name, properties)` | Record a view. The SDK does not track screens on its own. |
| `flush()` | Sends everything queued and waits. Throws if a batch could not be delivered. |
| `reset()` | Clears the stored user id and makes a new anonymous id. Call it on sign-out. It also stops push to this phone until the next `identify`. |
| `optOut()` and `optIn()` | Stop and resume tracking for this customer. The choice is stored on the phone. |
| `shutdown()` | Stops the instance without sending. Queued events stay on disk for the next instance. |

`anonymousId`, `userId` and `isOptedOut` read the current state.

Every event method also takes optional `userId`, `anonymousId`, `messageId`, `timestamp` and `context` arguments. Numbers are sent as doubles, so send identifiers larger than 2^53 as strings. A payload nested more than about 60 levels deep is refused.

## Identity

Before `identify`, events carry an anonymous id that the SDK creates and stores on the phone. After `identify`, events carry the user id.

* The `identify` call sends both the user id and the anonymous id, which lets Tranthor attach the customer's earlier anonymous activity to them.
* If a different customer identifies on the same phone, the SDK first replaces the anonymous id with a new one. The second customer never inherits the first customer's anonymous activity.
* An empty `userId` is treated as no user id.
* `reset()` clears the user id and starts a new anonymous id.

## Consent

`optOut()` discards everything queued and ignores later calls until `optIn()`. While opted out, `flush()` returns without sending anything. If the phone is registered for push, opting out also tells Tranthor to stop sending push to it.

That last message is the one thing the SDK sends while opted out. If it cannot be delivered, the SDK tries again when the app next starts or returns to the foreground, and on the next `optIn()` or `optOut()`. Until it is delivered, events queued after an `optIn()` wait behind it, and `flush()` throws instead of sending.

## Configuration

`Configuration` takes these options. Java code sets them on `Configuration.Builder`.

| Option | Default | Behavior |
| - | - | - |
| `writeKey` | Required | Your workspace's write key, sent as is. |
| `host` | `https://api.tranthor.com` | API host. |
| `batchSize` | `5` | Send when this many events are queued. |
| `flushIntervalMs` | `500` | Send this long after the first queued event. |
| `retries` | `5` | Retries after the first attempt. |
| `baseDelay` | `500` | Delay before the first retry in milliseconds; doubles each retry. |
| `automaticContext` | `true` | Adds the app, device, OS, screen, locale and timezone to each event. Keys you pass yourself win. |
| `maxQueueSize` | `10000` | The most events kept on the phone. When full, the oldest waiting events are dropped. |
| `storageNamespace` | `default` | Use a different name for each instance, and for each process in a multi-process app. |
| `onError` | none | Called once for each batch that is dropped, with its events, the HTTP status and the number of attempts. |

## Delivery

* Events are sent in batches. Network errors and HTTP 408, 425, 429 and 5xx responses are retried, and a `Retry-After` header is honoured up to 30 seconds. Other statuses, such as an invalid write key (401), are dropped after one attempt and reported through `onError`.
* Queued events are stored in the app's private storage, kept out of Auto Backup, and sent after a restart.
* The SDK sends what is queued when the app goes to the background. Android can stop a background app at any moment, so anything not yet delivered is sent the next time the app opens.
* The events passed to `onError` are the real events. For a phone registered for push, a dropped `Installation Registered` includes its push token, so do not log them or send them to a crash reporter. A rejected opt-out removal is reported with the token replaced by `<redacted>`.
* With the default settings a batch is dropped after about 15 seconds of failed attempts. An app that stays offline longer than that can lose events.

## Push

To send push to the app, add `tranthor-push` and follow [Install the SDK and bind push](https://docs.tranthor.com/integrations/channels/mobile-push.md#3-install-the-sdk-and-bind-push). The push module uses the same instance, write key and queue, so `identify`, `reset`, `optOut` and `optIn` keep the phone's registration in step with no extra calls. A phone is registered only while a customer is signed in: `identify` registers it and `reset()` removes it ([Who a phone belongs to](https://docs.tranthor.com/integrations/channels/mobile-push.md#who-a-phone-belongs-to)).

If you do not want the `POST_NOTIFICATIONS` permission merged into your app, remove it in your manifest:

```xml theme={null}
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" tools:node="remove" />
```

## Current limits

* No automatic screen tracking.
* No subscribe and unsubscribe methods. Use the [API](https://docs.tranthor.com/integrations/sources/api.md) or the [Web SDK](https://docs.tranthor.com/integrations/sdks/web.md) for those.
* The artifacts are not on Maven yet.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.