# Android

> Add Lemu to an Android app in Kotlin or Java: events, purchases, known users, screens, installs, deep links and the Play install referrer

URL: https://docs.lemuai.com/sdks/android

The Android SDK sends events, purchases, known users and screens from your app, and records installs, app opens and the links and Play Store campaigns that bring people in.

- Kotlin, and works from Java. Android 5.0 (API 21) or later.
- One small AndroidX dependency (`androidx.lifecycle:lifecycle-process`). No OkHttp, Retrofit or Gson, so nothing clashes with your app's versions.
- Events are kept on disk, batched, and retried when the network is back.
- No advertising id and no hardware ids.

You need the write key of an **App** source. See [Get a write key](https://docs.lemuai.com/sdks/overview#get-a-write-key).

## Install

The SDK is on Maven Central. In your app module's `build.gradle.kts`:
```kotlin
dependencies {
    implementation("com.lemuai:analytics:1.0.0")

    // Optional: attribute installs to the Play Store campaign that brought the user.
    implementation("com.android.installreferrer:installreferrer:2.2")
}
```

Make sure `mavenCentral()` is in your repositories. It is by default in new projects.

## Set up

Call `setup` once, in `Application.onCreate()`:

**Kotlin**

```kotlin
class MyApp : Application() {
    override fun onCreate() {
        super.onCreate()
        Lemu.setup(this, "lpk_...", LemuOptions(debug = BuildConfig.DEBUG))
    }
}
```

**Java**

```java
Lemu.setup(this, "lpk_...", LemuOptions.builder().debug(BuildConfig.DEBUG).build());
```

If your app runs code in more than one process, call `setup` in the main process only.

**Warning:** If the source lists [Allowed apps](https://docs.lemuai.com/website-pixel/overview#allowed-apps), add your app's package name (its `applicationId`). Builds with an `applicationIdSuffix`, such as `com.brand.app.debug`, send that id, so add it too or use a separate source for testing.

### Options

| Option | Default | What it does |
|---|---|---|
| `apiHost` | `https://app.lemuai.com` | Where to send events. Change it only if your source's setup steps show another host |
| `debug` | `false` | Logs every call, request and response to Logcat with the tag `Lemu` |
| `requireConsent` | `false` | Sends and stores nothing until `setConsent(true)` |
| `trackLifecycleEvents` | `true` | `app_installed`, `app_updated`, `app_opened`, `app_backgrounded` |
| `trackDeepLinks` | `true` | `deep_link_opened` for links that open an activity, and their campaign parameters |
| `collectInstallReferrer` | `true` | Reads the Play install referrer on first launch, when the library is in your app |
| `trackActivityScreens` | `false` | Sends a screen each time an activity starts |
| `flushAt` | `20` | Sends when this many events are queued |
| `flushIntervalSeconds` | `30` | Sends at least this often while events are queued |
| `maxQueueSize` | `1000` | The most events kept on the device while offline |

## Send events
```kotlin
Lemu.track(LemuEvent.ADD_TO_CART, mapOf(
    "value" to 999,
    "currency" to "INR",
    "content_ids" to listOf("SKU1"),
    "content_type" to "product",
))

Lemu.track("coupon_applied", mapOf("code" to "DIWALI10"))
```

Any event name works. For Meta's standard events, use the `LemuEvent` constants (`VIEW_CONTENT`, `ADD_TO_CART`, `INITIATE_CHECKOUT`, `PURCHASE` and the rest) so the names match exactly. See the [event reference](https://docs.lemuai.com/sdks/events).

Keep contact details such as email, phone and address out of event properties. Lemu removes them. Send them with `identify` instead.

## Purchases
```kotlin
Lemu.purchase(
    value = 1499.5,
    currency = "INR",
    orderId = "1042",
    contents = listOf(LemuContent(id = "SKU1", quantity = 1, itemPrice = 1499.5)),
    contentIds = listOf("SKU1"),
    numItems = 1,
    properties = mapOf("payment_method" to "cod"),
)
```

`purchase` sends a `Purchase` event straight away instead of waiting for the next batch. `value`, `currency` and `orderId` are what Lemu calculates journey and campaign revenue and ROI from.

**Always pass `orderId`.** The same order is often reported by the app, your website, Shopify or your server. Lemu counts one conversion per order id, so use the same id your backend and store use. Without it, every report counts as a separate sale. The app can be closed right after payment, so for the most reliable numbers [send purchases from your server too](https://docs.lemuai.com/website-pixel/standard-events#send-purchases-from-your-server-too). With the same order id, both count once.

With `debug` on, `track("Purchase", ...)` without `value`, `currency` or `order_id` logs a warning. The event is still sent.

## Identify users

When a user signs in or gives you their details:
```kotlin
Lemu.identify("user-829", mapOf(
    "email" to "asha@example.com",
    "phone" to "+919812345678",
    "first_name" to "Asha",
    "last_name" to "Rao",
))
```

The user id is sent with every later event until `reset()`. Send phone numbers in international format. On logout:
```kotlin
Lemu.reset() // new anonymous id, user id cleared
```

`Lemu.anonymousId` returns the random id the SDK created for this install.

## Screens
```kotlin
Lemu.screen("Checkout", mapOf("step" to 2))
```

Screens are stored as `screen_viewed` and aren't tracked automatically. To send one each time an activity starts, set `trackActivityScreens = true`, or register the tracker yourself to choose the names:
```kotlin
LemuActivityScreenTracker.register(this) { activity -> activity.title?.toString() }
```

Apps built on one activity with Compose or Fragments should call `Lemu.screen()` from their navigation.

## Deep links

Links that start an activity (`ACTION_VIEW` with a URL) are recorded as `deep_link_opened` with the `url` and `referrer`. UTM parameters (`utm_source`, `utm_medium`, `utm_campaign`, `utm_term`, `utm_content`) and `gclid` / `fbclid` in the link become the campaign for this and later events in the session, so a purchase made after tapping a campaign link is credited to that campaign.

Links delivered to an activity that is already running arrive in `onNewIntent`, which the SDK can't see. Record those yourself:
```kotlin
override fun onNewIntent(intent: Intent) {
    super.onNewIntent(intent)
    setIntent(intent)
    Lemu.trackDeepLink(intent)
}
```

## Install referrer

With `com.android.installreferrer:installreferrer` in your app (see [Install](#install)), the SDK reads the Play install referrer on the first launch. The campaign the user arrived with, for example from a Google Ads or Meta app campaign link to the Play Store, is added to `app_installed` and the rest of that first session. `app_installed` waits up to 10 seconds for the referrer. Without the library this is skipped. Set `collectInstallReferrer = false` to turn it off.

## App lifecycle events

Sent for you unless you set `trackLifecycleEvents = false`:

| Event | When | Properties |
|---|---|---|
| `app_installed` | First launch with the SDK | `version`, `build` |
| `app_updated` | First launch after the version changes | `version`, `build`, `previous_version`, `previous_build` |
| `app_opened` | Every time the app comes to the foreground | `from_background`, and `url` when a link opened the app |
| `app_backgrounded` | The app goes to the background. Queued events are sent then | |

If you add the SDK to an app people already have, the first launch after they update counts as `app_installed`.

## Consent and opt-out

If you need consent before tracking, for example under GDPR or the DPDP Act:
```kotlin
Lemu.setup(this, "lpk_...", LemuOptions(requireConsent = true))

// later, from your consent screen
Lemu.setConsent(true)   // sends what was held and starts tracking
Lemu.setConsent(false)  // discards held and queued events
```

Until consent, nothing is sent and nothing is written to the device, not even the anonymous id. Up to 50 events wait in memory and are sent once consent is given. A granted consent is remembered across launches; call `setConsent(false)` if the user withdraws it.

To let users switch tracking off entirely:
```kotlin
Lemu.optOut() // stops everything, clears queued events, remembered across launches
Lemu.optIn()  // turns it back on
```

## Debug logging
```kotlin
LemuOptions(debug = true)
```

Every call, request body and server response is logged to Logcat with the tag `Lemu`. Use it during development only, because event properties and traits appear in the log. A refused request (an unknown write key, or an app that isn't in **Allowed apps**) is logged too.

## Delivery

- Events are sent in batches of up to 50: every 30 seconds, when 20 are queued, when the app goes to the background, and right after a purchase. `Lemu.flush()` sends now.
- Events are stored in the app's no-backup files directory, so they survive restarts and aren't copied to other devices by Auto Backup. At most 1,000 are kept; when full, the oldest are dropped first, purchases last. Events older than 7 days are dropped.
- Failed requests are retried with increasing waits, up to 5 minutes apart, for up to 20 hours. Refused batches are dropped and logged in debug mode.
- The SDK never throws into your app. A bad argument is logged in debug mode and ignored.

The SDK ships its own ProGuard and R8 rules, so you don't need to add any.

## Google Play data safety

Your answers depend on how you use the SDK. With the SDK alone, this is what it collects and sends to Lemu:

| Play data type | Collected | When | Purpose |
|---|---|---|---|
| Device or other IDs | Yes | Always: a random anonymous id created by the SDK for this install (not an advertising id or a hardware id) | Analytics |
| App activity: App interactions | Yes | Always: lifecycle events, screens and the events you track | Analytics |
| App activity: Other actions | If you track them | Searches, sign-ups and other custom events | Analytics |
| Financial info: Purchase history | If you send purchases | Order value, currency, order id, items | Analytics |
| Personal info: User IDs | If you call `identify` with a user id | Your own user id | Analytics, App functionality |
| Personal info: Name, Email address, Phone number | If you pass them to `identify` | The traits you send | Analytics, and Advertising or marketing if you message users from Lemu |

Also sent with every event, and not a Play data type: app name, version, build and package name; device manufacturer, model and type; Android version; screen size and density; locale and time zone; the link that opened the app and its campaign parameters.

Not collected: advertising id (GAID), Android ID, IMEI, serial number, MAC address, location, contacts, photos, files and crash logs.

- **Is data encrypted in transit?** Yes, it is sent over HTTPS.
- **Is data shared?** Lemu processes it as your service provider. Under Play's definitions, that isn't sharing. If you forward conversions to an ad platform, that is.
- **Is collection optional?** Yes, if you use `requireConsent` or offer `optOut()`.

## Java

Every method is static on `Lemu` and has Java overloads:
```java
Map<String, Object> props = new HashMap<>();
props.put("value", 999);
props.put("currency", "INR");
Lemu.track(LemuEvent.ADD_TO_CART, props);
Lemu.purchase(1499.5, "INR", "1042");
```
