
# Android SDK

`com.kerdly:kerdly-sdk` measures installs, users, events and purchases in a native Android app and
sends them to your Kerdly project. Kerdly matches each install to the ad that brought it, then to
the revenue Google Play reports. Kotlin or Java, open source:
[github.com/Kerdly/kerdly-sdk](https://github.com/Kerdly/kerdly-sdk/tree/main/android).

Building with Expo or React Native? Use the [Expo SDK](https://kerdly.com/docs/sdks/expo.md) instead: it carries this
same Android code.

## Requirements

- Android 7.0 (API 24) or newer.
- The app's Android app in your Kerdly project. The product form at sign-up makes it when you tick
  **Android app**; with its package name, purchases and installs line up with Google Play.

## Before you start

Open the Android app's **Settings → SDK** in the dashboard. Its **app key** (`pk_live_…`) is
already made and shown in the code to paste. App keys are public; they ship inside your app. Use a
`pk_test_…` key for test builds, so their traffic stays out of your reports. Never put a server key
(`sk_…`) in the app; the SDK refuses it.

Each app key belongs to one application id. The SDK sends it with every request, and Kerdly refuses
a key used by another app. A build with an `applicationIdSuffix` (for example `.debug`) needs its
own key.

## Install

The SDK is on Maven Central:

```kotlin
// app/build.gradle.kts
dependencies {
    implementation("com.kerdly:kerdly-sdk:0.1.0")
}
```

Until 1.0 a minor version may change the API, so update minor versions deliberately.

## Configure

Call `configure` once, in `Application.onCreate`. It returns at once; the work happens on the SDK's
own thread.

```kotlin
class TallybirdApp : Application() {
    override fun onCreate() {
        super.onCreate()
        Kerdly.configure(
            this,
            KerdlyOptions(
                key = "pk_live_…",          // Tallybird Android's app key
                metaAppId = "1234567890",   // optional: your Facebook app id
            ),
        )
    }
}
```

| Option | Default | |
|---|---|---|
| `key` | required | The app's public key: `pk_live_…`, or `pk_test_…` for test builds. |
| `endpoint` | `https://app.kerdly.com/api` | Change it only if Kerdly support asks you to. |
| `environment` | `AUTO` | `PRODUCTION`, `SANDBOX` or `DEVELOPMENT`. `AUTO` is `DEVELOPMENT` for a debuggable build. |
| `collectAdvertisingId` | `true` | Read the Google advertising id when allowed. |
| `metaAppId` | none | Your Facebook app id. Turns on Meta install attribution. |
| `logLevel` | `WARN` | `NONE`, `ERROR`, `WARN`, `INFO` or `DEBUG`. |

Every method is safe from any thread and never throws. Calls made before `configure` run right
after it. Java callers get overloads.

## Users and consent

After sign-in, set your own user id; it is attached to every later event. Clear it on sign-out.
Use the same id your server and RevenueCat use.

```kotlin
Kerdly.setUserId(user.id)                          // after sign-in
Kerdly.setUserId(null)                             // on sign-out
Kerdly.setConsent(analytics = true, ads = true)    // reflect your consent screen
```

- `analytics = false` stops your custom and standard events; installs and opens are still counted.
- `ads = false` stops reading the advertising id and other ad-measurement signals.

## Standard events

Send these at the moments ad networks optimize on. Every argument is optional.

```kotlin
Kerdly.trackRegistration(method = "google")
Kerdly.trackStartTrial("tallybird_pro_weekly", value = 0.0, currency = "USD", transactionId = orderId)
Kerdly.trackSubscribe("tallybird_pro_weekly", value = 7.99, currency = "USD", transactionId = orderId)
Kerdly.trackPurchase("streak_freeze_5", value = 4.99, currency = "EUR", quantity = 1, transactionId = orderId)
```

- `value` is what the user paid, in `currency` (`0.0` for a free trial).
- `currency` is a three-letter ISO 4217 code. A `value` without a valid currency is dropped.
- `quantity` is a whole number of 1 or more.
- `properties` adds your own fields under the custom-event rules below.

These events tell the ad networks early. The revenue in your reports comes from Google Play itself,
so renewals and refunds need nothing from the app (see
[Client events, server events and deduplication](https://kerdly.com/docs/guides/events-and-dedupe.md)).

## Custom events

```kotlin
Kerdly.track("quiz_completed", mapOf("score" to 42, "level" to "hard"))
```

- Names and property keys: lowercase letters, digits and `_`, starting with a letter, at most 40
  characters.
- At most 25 properties. Values are strings (up to 256 characters), numbers or booleans.
- An invalid name drops the event; an invalid property is dropped on its own. With
  `logLevel = KerdlyLogLevel.DEBUG` logcat says why.

## Link purchases to the install

Renewals and refunds come from Google Play. To credit them to the right campaign, link each
purchase to the install:

1. Tell the SDK the `obfuscatedAccountId` your purchases carry (with Superwall, the user's alias).
2. After each completed purchase, pass it to `notifyPurchase`.

```kotlin
Kerdly.setAppAccountToken(accountId)

// in your billing client's or paywall's purchase callback
Kerdly.notifyPurchase(
    KerdlyPurchase(
        purchaseToken = purchase.purchaseToken,
        orderId = purchase.orderId,
        products = purchase.products,
        purchaseTime = purchase.purchaseTime,
        obfuscatedAccountId = purchase.accountIdentifiers?.obfuscatedAccountId,
    ),
)
```

Each purchase token is linked once; calling it again is harmless. For the whole store setup (Play
Console access, real-time notifications), see [Sell in a store app](https://kerdly.com/docs/guides/store-app.md).

If your app also sends conversions to Meta or TikTok itself, record each send with the event id the
network receives:

```kotlin
Kerdly.recordNetworkSend(KerdlyNetworkSend("meta", "StartTrial", eventId, 0.0, "USD"))
```

Ids from other SDKs can be attached with `Kerdly.setPartnerIds(mapOf("superwall_alias" to alias))`.

## Deep links

Forward every URL your app is opened with. The SDK records the open and returns the Kerdly
parameters it found; your app keeps its own navigation. Custom schemes and App Links both work,
including [Kerdly links](https://kerdly.com/docs/guides/web-to-app.md).

```kotlin
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    intent?.dataString?.let { Kerdly.handleUrl(it) }
}

override fun onNewIntent(intent: Intent) {
    super.onNewIntent(intent)
    intent.dataString?.let { Kerdly.handleUrl(it) }
}
```

`handleUrl` returns a `KerdlyDeepLink` (`url`, `cpp`, `ppid`, `clickId`, `visitId`, `campaignIds`) or
null.

## Attribution

```kotlin
Kerdly.onAttribution { attribution ->
    // on the main thread: now if known, and again if it changes
    Log.d("App", "${attribution.network} ${attribution.campaign}")
}

val current = Kerdly.attribution   // null until known
val installId = Kerdly.installId   // give it to your backend to tie accounts to installs
```

`Kerdly.flush()` sends queued events now.

## Permissions and manifest

The library adds to your merged manifest:

- `android.permission.INTERNET`;
- `com.google.android.gms.permission.AD_ID`;
- `<queries>` for the Facebook, Instagram and Facebook Lite apps, used for Meta install attribution
  on Android 11 and newer.

Apps for children or in the Families program should remove the advertising id permission and turn
its collection off:

```xml
<uses-permission android:name="com.google.android.gms.permission.AD_ID" tools:node="remove"/>
```

```kotlin
KerdlyOptions(key = "pk_live_…", collectAdvertisingId = false)
```

The SDK's data is excluded from Auto Backup, so no backup rules are needed. ProGuard and R8 rules
come with the library.

## Data and privacy

What the SDK sends, for your Google Play data safety form:

| Data | When |
|---|---|
| An install id generated by the SDK | always |
| Device model, OS version, language, time zone, app version, installer | always |
| Google Play and Meta install referrers | once per install |
| App events you track | with `analytics` consent |
| Purchase identifiers | when you call `notifyPurchase` |
| Google advertising id | with `ads` consent and `collectAdvertisingId`, unless the user limited ad tracking |
| Public IPv6 address | with `ads` consent |
| The user id you set | when you call `setUserId` |
| The Google advertising id and install referrer, sent to TikTok to ask which ad led to the install | only with deferred deep links on in your Kerdly project, and `ads` consent |

The SDK never collects names, email addresses, phone numbers or contacts, and never reads location
services (GPS).

## Check it's working

1. Set `logLevel = KerdlyLogLevel.DEBUG` and run the app on a device or emulator.
2. Filter logcat for `Kerdly`: the SDK logs what it sends and any error Kerdly answers with.
3. In the dashboard, the Android app's **Onboarding** page shows the SDK step with the time of the
   last event. Events arrive within a minute; `Kerdly.flush()` sends at once.

## Troubleshooting

- Kerdly answers `bundle_mismatch`: the key belongs to another Kerdly app, or the application id
  (with its suffix) doesn't match this app's.
- Kerdly answers `bad_key` or `key_revoked`: the key was mistyped or revoked; create a new one under
  **Settings → SDK**.
- Questions or problems: [open an issue](https://github.com/Kerdly/kerdly-sdk/issues) or contact
  Kerdly support. Never post your keys.

## Agent checklist

- [ ] `com.kerdly:kerdly-sdk:0.1.0` in the app module's dependencies.
- [ ] `Kerdly.configure` once in `Application.onCreate`, with the Android app's `pk_live_` key
      (never an `sk_` key), and `metaAppId` if the app runs Meta ads.
- [ ] `setUserId` after sign-in and `null` on sign-out, with the id your server uses.
- [ ] `trackRegistration` on sign-up; `trackStartTrial`, `trackSubscribe` or `trackPurchase` from the
      purchase flow, with `productId`, `value`, `currency` and `transactionId`.
- [ ] `setAppAccountToken` and `notifyPurchase` for every Google Play purchase.
- [ ] `handleUrl` in `onCreate` and `onNewIntent` of the activity that receives links.
- [ ] Existing analytics and attribution SDKs left in place.

---

Source: https://kerdly.com/docs/sdks/android. Index of all docs: https://kerdly.com/llms.txt
