# Connect your Android app

> Add the Releva Kotlin SDK from JitPack, initialise the client with your Access Token, extend the SDK's Firebase messaging service, handle navigation, track screens with page tokens and check in Releva that data arrives.

The Releva Kotlin SDK (`sdk-kotlin`) connects a native Android app to Releva: screen and product tracking, product blocks, banners, stories, NPS surveys, app push through Firebase Cloud Messaging and the App Inbox.

> **Caution**
>
> The SDK steps on this page describe version 1.8.0 of the Android SDK. If your version is newer, check its release notes for changed names.

## Before you start

* Minimum SDK API 24 (Android 7.0), target SDK 36, Kotlin 2.0 or later, Gradle 8.9 or later.
* Your shop’s **Access Token** from **Settings › Shop & Integration › General**: [Find your Access Token and Secret Key](https://releva.ai/documentation/guides/shop-settings/find-your-api-keys/). Never put the **Secret Key** in the app.
* One page token per screen you want to track or personalise, from the **Token:** bar on **Personalization › Product Blocks**: [Pages and tokens](https://releva.ai/documentation/learn/product-blocks/how-product-blocks-work/#pages-and-tokens).
* For push: a Firebase project with `google-services.json`, and its service account uploaded in Releva: [Add your Firebase credentials for app push](https://releva.ai/documentation/integrations/mobile/add-firebase-credentials-for-app-push/).

## Install

Add JitPack in `settings.gradle.kts`:

```plaintext
dependencyResolutionManagement {
    repositories {
        google()
        mavenCentral()
        maven { url = uri("https://jitpack.io") }
    }
}
```

Add the dependency in the app module’s `build.gradle.kts`, plus Firebase messaging for push:

```plaintext
dependencies {
    implementation("com.github.Releva-ai:sdk-kotlin:1.8.0")
    implementation("com.google.firebase:firebase-messaging:23.4.0")
    implementation("androidx.core:core-ktx:1.12.0")
    implementation("com.squareup.okhttp3:okhttp:4.12.0")
}
```

Add the notification permission Android 13 and later require:

```plaintext
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
```

## Configure

### 1. Client, device id, profile id

Create the client once in your `Application` class and register the class in the manifest (`android:name=".MyApplication"`):

```plaintext
class MyApplication : Application() {
    lateinit var relevaClient: RelevaClient
        private set
    private val applicationScope = CoroutineScope(SupervisorJob() + Dispatchers.Main)


    override fun onCreate() {
        super.onCreate()
        relevaClient = RelevaClient(
            context = applicationContext,
            realm = "",                         // "" unless Releva gives you one
            accessToken = "<yourAccessToken>",  // Settings › Shop & Integration › General
            config = RelevaConfig.full()
        )
        applicationScope.launch {
            relevaClient.setDeviceId(getDeviceId())
            // After login: relevaClient.setProfileId("<profileId>")
            relevaClient.enablePushEngagementTracking()


            // Register the current push token at every launch, once the ids are set.
            FirebaseMessaging.getInstance().token.addOnSuccessListener { token ->
                applicationScope.launch {
                    try {
                        relevaClient.registerPushToken(DeviceType.ANDROID, token)
                    } catch (e: Exception) {
                        Log.e("MyApplication", "Error registering push token", e)
                    }
                }
            }
        }
    }


    private fun getDeviceId(): String =
        Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID)
}
```

Register the push token at every launch, as above. `onPushTokenGenerated` (step 2) runs only when Firebase issues a new token, not when an app update adds Releva to an install that already has one, so without the launch call that device never gets a push.

Almost every SDK call is a `suspend` function; call them from `lifecycleScope` or `viewModelScope`. On **login** `setProfileId(userId)` merges the anonymous history into the account. On **logout** assign a fresh anonymous id with `skipMergeWithPreviousProfileId = true` and register the push token again; do not use `setProfileId("")`:

```plaintext
relevaClient.setProfileId(UUID.randomUUID().toString(), skipMergeWithPreviousProfileId = true)
FirebaseMessaging.getInstance().token.addOnSuccessListener { token ->
    CoroutineScope(Dispatchers.IO).launch { relevaClient.registerPushToken(DeviceType.ANDROID, token) }
}
```

### 2. Push: extend the SDK messaging service

The SDK ships a Firebase messaging service that displays the notification, tracks engagement and routes the tap. Subclass it and register it in the manifest:

```plaintext
class MyFirebaseMessagingService : RelevaFirebaseMessagingService() {
    override fun getMainActivityClass(): Class<*> = MainActivity::class.java
    override fun getNotificationIcon(): Int = R.drawable.ic_notification
    override fun getDefaultNotificationTitle(): String = "My App"
    override fun onPushTokenGenerated(token: String) {
        val relevaClient = (application as MyApplication).relevaClient
        CoroutineScope(Dispatchers.IO).launch {
            try { relevaClient.registerPushToken(DeviceType.ANDROID, token) }
            catch (e: Exception) { Log.e(TAG, "Error registering push token", e) }
        }
    }
}
```

```plaintext
<service android:name=".push.MyFirebaseMessagingService" android:exported="false">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>
```

### 3. Navigation from a tap

A push carries a target of `screen` (with parameters), `url` (opened in the browser) or none (your main screen). Implement `NavigationHandler` for the screen case, register it in your main Activity and hand the SDK both the launching intent and later ones:

```plaintext
class AppNavigationHandler(private val navController: NavController) : NavigationHandler {
    override fun navigateToScreen(screenName: String, parameters: Bundle) {
        when (screenName) {                 // the Screen name set under Mobile Targeting in the push form
            "cart" -> navController.navigate(R.id.cartFragment)
            "product_details" -> navController.navigate(R.id.productFragment, parameters)
            else -> navController.navigate(R.id.homeFragment)
        }
    }
}


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val navController = findNavController(R.id.nav_host_fragment)
        NavigationService.getInstance().setNavigationHandler(AppNavigationHandler(navController))
        NavigationService.getInstance().handleNotificationNavigation(this, intent)   // opened from a push
    }
    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        NavigationService.getInstance().handleNotificationNavigation(this, intent)   // already running
    }
}
```

Without the `onNewIntent` override, taps work from a cold start but do nothing while the app is open.

### 4. Track screens with page tokens

Screen, product, search and checkout views go through one call: build a `PushRequest` and call `relevaClient.push(request)`.

```plaintext
lifecycleScope.launch {
    val request = PushRequest()
        .url("myapp://product/details")
        .screenToken("<productPageToken>")
        .productView(ViewedProduct(productId = productId, custom = CustomFields.empty()))
        .pageCategories(listOf("Shoes"))
    val response = relevaClient.push(request)
    if (response.hasRecommenders) renderRecommendations(response.recommenders)
}


// Cart and wishlist are stateful; the cart clears itself after a checkout.
relevaClient.setCart(Cart.active(cartProducts))
relevaClient.setWishlist(productIds.map { WishlistProduct(id = it) })
relevaClient.push(PushRequest().url("myapp://checkout/success").cart(Cart.paid(cartProducts, orderId = orderId)))
```

Two fields are easy to get wrong. `screenToken` must be a page token copied from **Personalization › Product Blocks**, not a name you invent; a screen sent with `"product_detail"` records no page view and returns no banners or stories, and Releva answers `200` either way. `url` must be a full URL with a scheme, your own or `https://`; a bare path is rejected. Both may be `null`.

The main builder methods: `url`, `screenToken`, `productView`, `pageProductIds`, `pageCategories`, `pageQuery`, `pageFilter`, `locale`, `currency`, `customEvents`, `cart`. Single custom events go through `trackCustomEvent(CustomEvent(action, products, tags, custom))`. The SDK returns recommendation data and renders none of it.

### 5. On-screen content

* **Banners**: `BannerDisplayManager(client, targetSelector, onLinkTap)` then `attach(fragment)` or `attach(activity)`. `onLinkTap` is required; the SDK never navigates for you.
* **Stories**: `StoryDisplayManager.setClient`, `setOnLinkTap` (before `attach`), `attach(activity)`; plus a `StoryManagerService` you `initialize(response.stories)` and drive with `onCartChanged()`, `onWishlistChanged()`, `onScrollPercentageReached(percentage)`; `dispose()` cancels pending timers.
* **NPS**: `NpsDisplayManager.setOnSubmit { token, score, comment -> relevaClient.submitNpsResponse(token, score, comment) }`, optional `setOnSkip`, then `attach(this)` from a `FragmentActivity`; `relevaClient.trackEvent("checkout_complete")` triggers or cancels surveys.
* **App Inbox**: collect `relevaClient.inbox.state` (`messages`, `unreadCount`, `hasMore`, `isLoading`) with `repeatOnLifecycle`; `refresh()`, `loadMore()`, `refreshIfStale()` on resume (network only when the cache is older than five minutes); `markAsRead`, `markAllAsRead`, `deleteMessage` update the UI immediately and roll back on failure.

Configuration presets: `RelevaConfig.full()`, `trackingOnly()`, `pushOnly()`, or `RelevaConfig(enableTracking, enableScreenTracking, enableInAppMessaging, enablePushNotifications, enableAnalytics)`.

## Verify

Run the app, accept the notification permission and open a screen with a page token. Then follow [Check that your mobile app is connected](https://releva.ai/documentation/integrations/mobile/check-that-your-mobile-app-is-connected/): the **Push Notification Subscribe** event is tagged `device_android` and the profile shows an **ANDROID** badge.

## Troubleshooting

**No Push Notification Subscribe event.** `registerPushToken` was not reached: `onPushTokenGenerated` is not overridden, the service is not registered in the manifest, or the notification permission was denied on Android 13 and later.

**A tap does nothing while the app is open.** `onNewIntent` is missing.

**No banners, stories or product blocks, and no Viewed Page event.** The `screenToken` is not a page token. Copy it from **Personalization › Product Blocks**.

**`400` from the push endpoint.** Messages are listed in the [push notifications reference](https://releva.ai/documentation/reference/push-notifications/overview/#register-a-mobile-app-push-token).

**The push is sent but never arrives.** Only tokens registered as `android` or `ios` are targeted. After **Force stop** in the Android settings, Android blocks pushes until the app is opened again.

## What syncs

Endpoints and identifiers are the same as for the other SDKs.

| Data                                                                        | Endpoint                                                                                       | When                                                                                                                                                  |
| --------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| Screen, product, search views; custom events; cart, wishlist; checkout      | `POST /api/v0/push`                                                                            | `push(request)`, `trackCustomEvent`; `setCart`/`setWishlist` changes                                                                                  |
| App push token                                                              | `POST /api/v0/appPush/tokens`                                                                  | `registerPushToken(DeviceType.ANDROID, token)` from `onPushTokenGenerated` and after logout. Writes a **Push Notification Subscribe** event each time |
| Push tap                                                                    | `GET <callbackUrl>` from the push data                                                         | Handled by `RelevaFirebaseMessagingService`                                                                                                           |
| Banner impressions and actions, story actions                               | `POST /api/v0/impressions`, `POST /api/v0/push/events`                                         | Display managers                                                                                                                                      |
| NPS answer                                                                  | `POST /api/v0/nps/{token}/submissions`                                                         | `submitNpsResponse`                                                                                                                                   |
| App Inbox                                                                   | `GET /api/v0/inbox/messages`, `GET /api/v0/inbox/unread-count`, read, read-all, delete, action | `relevaClient.inbox`                                                                                                                                  |
| Products, orders paid outside the app, refunds, profile attributes, consent | not sent by the SDK                                                                            | Your backend: [What your backend still sends](https://releva.ai/documentation/integrations/mobile/mobile-sdks-overview/#what-your-backend-still-sends)                 |

## Next steps

* [Add your Firebase credentials for app push](https://releva.ai/documentation/integrations/mobile/add-firebase-credentials-for-app-push/): Upload the Firebase service account Releva sends app push through.
* [Check that your mobile app is connected](https://releva.ai/documentation/integrations/mobile/check-that-your-mobile-app-is-connected/): Confirm in the Releva admin that push token registrations arrive.
* [Mobile SDKs overview](https://releva.ai/documentation/integrations/mobile/mobile-sdks-overview/): See what every SDK sends and what your backend still has to send.
* [How the App Inbox works](https://releva.ai/documentation/learn/inbox/how-the-app-inbox-works/): Learn how inbox messages reach your app and stay in sync.