# Android SDK

Source: https://kirora.io/docs/sdks/android

Track signed-in customer activity in your Android app and send push notifications with images, buttons and tap reports.

Use the Android SDK to see what customers do in your app and reach them with push. Track events and visits for segments and journeys, register devices through Firebase Cloud Messaging, and report opens and clicks without extra code. It's written in Kotlin and keeps events on the device while it's offline.

## Before you start

- **Android 7.0 (API 24) or later** at runtime, with **Kotlin 2.1 or later**. Your app must compile against API 35 or later (`compileSdk = 35`).
- **A server you control** that can sign a token for the signed-in user. Every Kirora server library does it in one call.
- **For push:** a Firebase project for your app, and an Android push app in Kirora. See [Set up push](https://kirora.io/docs/guides/getting-started/set-up-push), and [Get your Apple and Firebase keys](https://kirora.io/docs/guides/getting-started/get-push-keys) if you haven't used either before.

## How it works

The SDK runs on your users' phones, so it never holds an API key. It uses two things instead:

- **A client key** (`kirora_pk_…`): public, safe to ship in the app. It says which workspace the events belong to.
- **A user token**: signed by your server for the user who is signed in, so nobody can send events as someone else. The SDK asks your server for one at sign-in and before one expires.

> [!WARNING]
> Never put an API key or the SDK token secret in your app, its resources, `BuildConfig` or its logs. Both stay on your server.

## 1. Create your keys

In the dashboard, open **Developer → SDK**. An owner, admin or developer chooses **Set up the SDK**, which creates both keys. The **Secret key** is your token secret, shown only once: put it in your server's environment as `KIRORA_SDK_TOKEN_SECRET`. The **Public key** is your client key, and goes in your app.

## 2. Add a token route to your server

Add a route that signs a token for the user of the current session. Take the user's id from your own session, never from the app's request:

```ts
// Express, with the Node.js library
import { createUserToken } from '@kirora/node';

app.get('/kirora-token', requireSignedIn, (request, response) => {
  response.set('Cache-Control', 'no-store');
  response.type('text/plain').send(createUserToken(process.env.KIRORA_SDK_TOKEN_SECRET!, String(request.user.id)));
});
```

Return `401` when nobody is signed in. The [Go](https://kirora.io/docs/sdks/go#sign-tokens-for-the-web-sdk), [.NET](https://kirora.io/docs/sdks/dotnet#sign-tokens-for-the-web-sdk), [PHP](https://kirora.io/docs/sdks/php#sign-tokens-for-the-web-sdk) and [Laravel](https://kirora.io/docs/sdks/laravel#sign-tokens-for-the-web-sdk) libraries sign the same token. In any other language, sign an HS256 JWT with the token secret, with `sub` set to your id for the user (their contact's `externalId`) and `exp` no more than 24 hours after `iat`. An hour is a good lifetime.

## 3. Install the SDK

The SDK comes in two libraries from Maven Central. Most apps want the one with push:

| Library | Includes |
| --- | --- |
| `io.kirora:android-sdk-push` | Everything in core, plus Firebase Cloud Messaging, notification rendering and taps. |
| `io.kirora:android-sdk` | Sign-in, events, screens, visits and consent. No Firebase. |

```kotlin
// settings.gradle.kts
dependencyResolutionManagement {
    repositories {
        google()
        mavenCentral()
    }
}

// app/build.gradle.kts
dependencies {
    implementation("io.kirora:android-sdk-push:0.1.0")
}
```

The Kotlin package is `com.kirora.androidsdk`. For a React Native, Expo or Flutter app, use the [React Native](https://kirora.io/docs/sdks/react-native), [Expo](https://kirora.io/docs/sdks/expo) or [Flutter](https://kirora.io/docs/sdks/flutter) SDK instead. It includes this one.

## 4. Start the SDK

Create one client in your `Application` class, and name that class in your manifest:

```kotlin
import android.app.Application
import com.kirora.androidsdk.Kirora
import com.kirora.androidsdk.model.KiroraOptions

class App : Application() {
    lateinit var kirora: Kirora
        private set

    override fun onCreate() {
        super.onCreate()
        kirora = Kirora(
            this,
            KiroraOptions(
                clientKey = "kirora_pk_…",                       // public: safe in the app
                fetchUserToken = { MyApi.kiroraToken() }         // your route from step 2
            )
        )
    }
}
```

```xml
<application android:name=".App" … />
```

`MyApi.kiroraToken()` is your app's signed-in request to the route from step 2: a `suspend` function that returns the token as plain text and throws when the request fails, so the SDK keeps the events and tries again later. Starting early in `onCreate` lets push taps reach your app. Creating the client never prompts for permission or waits on the network.

## 5. Sign users in and out

From a coroutine:

```kotlin
// Each time the app starts with a signed-in user, and right after they sign in.
try {
    kirora.identify()
} catch (error: com.kirora.androidsdk.model.KiroraError) {
    // Keep the app usable; try again once the user or the network is back.
}

// Before your own sign-out.
kirora.logout()
```

The SDK keeps the token in memory only, so call `identify()` again on every signed-in start. Nothing is sent before sign-in: events tracked earlier wait on the device and go as the user who signs in next. An event tracked while one user is signed in never becomes another user's. `logout()` tries for up to five seconds to send what's waiting and stop this device's pushes for the user, then forgets the rest. Offline, stopping pushes is retried while the app runs, for up to 24 hours.

If the token fails later, in the background, the SDK calls `onAuthenticationFailed` on the main thread with `FETCH_FAILED` or `REFUSED`. Use it to sign the user out, or ask them to sign in again.

From Java, or anywhere without coroutines, use the callback forms: `identifyAsync`, `logoutAsync`, `flushAsync` and the rest.

## 6. Track what they do

```kotlin
kirora.track(
    "Order Completed",
    mapOf("order_id" to "1042", "total" to 46.5, "currency" to "USD")
)
kirora.trackScreenView("Checkout")
```

`track()` returns at once and never throws: events go in [batches](#delivery-and-storage). Properties take strings, numbers, booleans, `null`, lists and maps with string keys; dates are sent as ISO 8601 strings and enums as their names. Name events as the [naming guide](https://kirora.io/docs/sdks/web#naming-events) describes, so journeys and segments can match them.

## 7. Check it works

Sign in on a device or an emulator, track an event, then call `kirora.flush()` to send it now. Open the contact in **Contacts** in Kirora: the event is on their activity. While you build, set `logLevel = LogLevel.DEBUG` to see each event and batch in Logcat.

## Ask for tracking consent

Where the law asks for consent before tracking, start the SDK with `requireTrackingConsent = true` and pass on the user's answer:

```kotlin
kirora.setTrackingConsent(true)  // they agreed
kirora.setTrackingConsent(false) // they refused, or withdrew
```

Nothing is tracked or kept until the user agrees. The answer is remembered on the device, and `false` deletes events still waiting. Tracking consent covers events and visits only: push permission and push consent are separate, below.

## Send push notifications

### Turn push on

1. **In Firebase**, add your Android app to a Firebase project and put its `google-services.json` in your app module (`app/`). Then apply the Google Services Gradle plugin:

   ```kotlin
   // settings.gradle.kts or the project's build.gradle.kts
   plugins {
       id("com.google.gms.google-services") version "4.6.0" apply false
   }

   // app/build.gradle.kts
   plugins {
       id("com.google.gms.google-services")
   }
   ```
2. **In Kirora**, add an Android push app and upload the Firebase project's service account file. See [Set up push](https://kirora.io/docs/guides/getting-started/set-up-push).
3. **In your app**, use `io.kirora:android-sdk-push` and add `push = KiroraPushOptions()` to the client's options. If the workspace has several Android push apps, choose one with `KiroraPushOptions(pushAppId = "…")`.
4. **Ask for permission** at a moment the user understands, after they've signed in. Android 13 and later show a prompt; earlier versions allow notifications by default:

```kotlin
kirora.requestPushPermission(activity) { permission ->
    // GRANTED, DENIED, UNANSWERED or UNSUPPORTED
}

// Later, from a coroutine, once they've opted in to marketing:
kirora.setPushConsent(true)
```

The device is registered at `identify()` and when permission is granted, and refreshed when the user or token changes. Permission is enough for a transactional push, such as an order update. Campaign and journey push also need the user's marketing consent, which `setPushConsent()` records. It throws if Kirora didn't record it, so only show the choice as saved once it returns.

The push library brings its own Firebase messaging service and the notification permission, so there's nothing to add to your manifest.

### How notifications look

The SDK draws each Kirora push itself, with an image and up to two buttons when the push has them. Set how it looks in `KiroraPushOptions`:

```kotlin
push = KiroraPushOptions(
    smallIconResId = R.drawable.ic_notification,
    accentColor = 0xFF5B4CF5.toInt(),
    defaultChannelName = "Updates"
)
```

Pushes go to the `kirora_default` channel unless one names another. To send to your own channels, such as *Orders* or *Offers*, create them in your app, then name them on the push. Sound and importance follow each channel's settings.

In the foreground, a Kirora push is shown unless `onForegroundNotification` returns `false` for it.

### Handle taps and links

A tap opens the app and is reported as an open, or a click when it has a link. An app link or one of your app's own schemes opens in the app; anything else opens with the system. To route links yourself, use `handleDeepLink`:

```kotlin
KiroraOptions(
    clientKey = "kirora_pk_…",
    handleDeepLink = { url ->
        router.open(url) // return true when your app handled it
    }
)
```

To act on a tap in your own code, with the push's data:

```kotlin
val onTap: (Map<String, String>) -> Unit = { data ->
    // data: the push's data, your own keys included
}
kirora.addNotificationClickListener(onTap)

kirora.removeNotificationClickListener(onTap) // when the screen or object that added it goes away
```

Remove a listener with the same function you added. A tap that launched the app is held for the first listener you add. `javascript:`, `file:`, `content:`, `intent:` and `data:` links are never opened. Treat a push's data as untrusted input, and check every link your router accepts.

### Use your own messaging service

If your app already has a `FirebaseMessagingService`, it takes priority over Kirora's. Forward both callbacks to the SDK:

```kotlin
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import com.kirora.androidsdk.push.fcm.KiroraPush

class AppMessagingService : FirebaseMessagingService() {
    override fun onMessageReceived(message: RemoteMessage) {
        if (KiroraPush.handleMessage(this, message)) return
        // another provider's message
    }

    override fun onNewToken(token: String) {
        KiroraPush.onNewToken(this, token)
    }
}
```

If you keep Kirora's service instead, register `KiroraPush.setFallbackMessageHandler` early to receive messages that aren't Kirora's. Use one or the other, not both, or a message is handled twice.

### Test a push

Use a device or an emulator with Google Play services. Sign in, allow notifications, then send yourself a test from the push step's **Send test**. To check delivery and tap reports, send a campaign to a segment with just you in it: test sends aren't counted.

## Visits and app events

- **Visits:** a visit starts with a `Session Started` event, and every event in it carries the same `context.sessionId`. Activity and time in the foreground keep it going; after 30 minutes away, the next activity starts a new visit. Visits are on by default; `trackSessions = false` turns them off.
- **App events:** `trackAppLifecycle = true` records `Application Installed`, `Application Updated`, `Application Opened` and `Application Backgrounded`. It's off by default.
- **Screens:** call `trackScreenView()` from the screens you care about. Screens aren't tracked automatically.
- **Context:** each event carries the app's name, version, build and package, the Android version, the screen size, the device's language and time zone, its manufacturer and a random id for this install. Never a device model, carrier or advertising id.

To remove a field, or drop an event, before it's stored, use `beforeSend`:

```kotlin
beforeSend = { event ->
    event.copy(properties = event.properties - "email") // or null to drop it
}
```

## Options

| Option | Default | What it does |
| --- | --- | --- |
| `clientKey` | Required | The workspace's public key (`kirora_pk_…`). |
| `fetchUserToken` | None | Asks your server for a user token. Times out after 30 seconds. |
| `push` | Off | `KiroraPushOptions()` to register for push, with its look and push app. |
| `requireTrackingConsent` | `false` | Track and keep nothing until `setTrackingConsent(true)`. |
| `trackSessions` | `true` | Record `Session Started` and the visit on every event. |
| `trackAppLifecycle` | `false` | Record install, update, open and background events. |
| `handleDeepLink` | None | Routes a push's link. Return `true` when your app handled it. |
| `onAuthenticationFailed` | None | Called on the main thread when the user's token fails in the background. |
| `beforeSend` | None | Edits or drops each event before it's stored. |
| `logLevel` | `ERROR` | `NONE`, `ERROR` or `DEBUG`. |
| `apiUrl` | `https://api.kirora.io` | For tests against a mock server. |

`KiroraPushOptions` takes `pushAppId`, `smallIconResId`, `accentColor`, `defaultChannelId`, `defaultChannelName`, `onForegroundNotification` and `allowedLinkSchemes`, which limits the links the SDK opens itself.

## Methods

| Method | Does |
| --- | --- |
| `identify(token?)` | Signs the user in, with a token from `fetchUserToken` unless given one; registers for push if allowed; sends waiting events. |
| `logout()` | Tries for up to five seconds to send what's waiting and stop this device's pushes, then forgets the user. |
| `track(name, properties)` | Records an event. Returns at once. |
| `trackScreenView(name)` | Records `Screen Viewed`. |
| `setTrackingConsent(granted)` | Records the user's tracking answer. |
| `requestPushPermission(activity)` | Shows Android's prompt when needed and registers the device. |
| `getPushStatus()` | `ENABLED`, `DISABLED`, `DENIED`, `UNANSWERED` or `UNSUPPORTED`. Never prompts. |
| `setPushEnabled(enabled)` | Turns push on or off for this device, for every user. Never prompts. |
| `setPushConsent(granted)` | Records the signed-in user's consent to marketing push. |
| `flush()` | Sends waiting events now. Rarely needed. |
| `getState()` | What the SDK knows now, for debugging: signed in, device id, queued events. |
| `destroy()` | Stops the client. Waiting events stay for the next one. |
| `addNotificationClickListener(listener)` | Hears taps on Kirora pushes and their buttons. |

The `suspend` methods each have a callback form for Java: `identifyAsync`, `logoutAsync`, `flushAsync`, `setPushConsentAsync`, `getPushStatusAsync`, `setPushEnabledAsync` and `getStateAsync`. Errors are `KiroraApiError` (with `status`, `code` and `retryAfterMs`), `UserTokenError` when `fetchUserToken` fails, or `KiroraError`.

## Delivery and storage

- **Batches:** events go when 20 are waiting, otherwise within 30 seconds, and when the app goes to the background. A batch holds up to 100.
- **Retries:** when the device is offline or Kirora is busy, the SDK retries with growing gaps, never sooner than Kirora's `Retry-After`. Each event keeps its idempotency key, so a retry is recorded once.
- **On the device:** up to 1,000 events wait in the app's private storage and survive restarts, excluded from backups. Beyond that, the oldest are dropped. Tokens are kept in memory only.
- **Plan limit:** past your plan's tracked events for the month, Kirora refuses further events and the SDK drops them. Sign-in and push still work.
- **Privacy:** the SDK collects no device model, carrier, hardware or advertising id; its device id is random. Your Play Store data safety form still needs to cover the events you send.

## Troubleshooting

| Symptom | Check |
| --- | --- |
| Events stay on the device | The user is signed in with `identify()`, tracking consent is given, and your token route returns a token. |
| `401` or a token error | The token is signed with this workspace's secret, names the signed-in user and hasn't expired. |
| Build fails on `compileSdk` | Your app compiles against API 35 or later. |
| No push token | `google-services.json` and the Google Services plugin, and Google Play services on the device. |
| Permission granted, status disabled | The user is signed in and push is on for the device; check Logcat with `LogLevel.DEBUG`. |
| Pushes don't arrive in your own service | Forward `onMessageReceived` and `onNewToken` to `KiroraPush`. |
| No delivery or tap reports | Send a campaign, not a test: test sends aren't counted. |

## Next steps

- [Set up push](https://kirora.io/docs/guides/getting-started/set-up-push) — add the Android push app the SDK registers with.
- [Create a push notification](https://kirora.io/docs/guides/messaging/push/create-a-push-notification) — write one, with an image and buttons.
- [E-commerce events](https://kirora.io/docs/api/ecommerce-events) — the standard names and properties for commerce events.
- [Source on GitHub](https://github.com/kiroratech/kirora-android) — the full reference, changelog and issues.