LemuAIDocs

Settings · 7 min read

Android

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

Open in ChatGPTOpen in ClaudeMarkdown

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.

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
class MyApp : Application() {
    override fun onCreate() {
        super.onCreate()
        Lemu.setup(this, "lpk_...", LemuOptions(debug = BuildConfig.DEBUG))
    }
}

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

If the source lists 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#

OptionDefaultWhat it does
apiHosthttps://app.lemuai.comWhere to send events. Change it only if your source's setup steps show another host
debugfalseLogs every call, request and response to Logcat with the tag Lemu
requireConsentfalseSends and stores nothing until setConsent(true)
trackLifecycleEventstrueapp_installed, app_updated, app_opened, app_backgrounded
trackDeepLinkstruedeep_link_opened for links that open an activity, and their campaign parameters
collectInstallReferrertrueReads the Play install referrer on first launch, when the library is in your app
trackActivityScreensfalseSends a screen each time an activity starts
flushAt20Sends when this many events are queued
flushIntervalSeconds30Sends at least this often while events are queued
maxQueueSize1000The 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.

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. 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.

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), 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:

EventWhenProperties
app_installedFirst launch with the SDKversion, build
app_updatedFirst launch after the version changesversion, build, previous_version, previous_build
app_openedEvery time the app comes to the foregroundfrom_background, and url when a link opened the app
app_backgroundedThe 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.

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 typeCollectedWhenPurpose
Device or other IDsYesAlways: a random anonymous id created by the SDK for this install (not an advertising id or a hardware id)Analytics
App activity: App interactionsYesAlways: lifecycle events, screens and the events you trackAnalytics
App activity: Other actionsIf you track themSearches, sign-ups and other custom eventsAnalytics
Financial info: Purchase historyIf you send purchasesOrder value, currency, order id, itemsAnalytics
Personal info: User IDsIf you call identify with a user idYour own user idAnalytics, App functionality
Personal info: Name, Email address, Phone numberIf you pass them to identifyThe traits you sendAnalytics, 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");

Was this page helpful?