Connect your Android app
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.
Before you start
Section titled “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. 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.
- For push: a Firebase project with
google-services.json, and its service account uploaded in Releva: Add your Firebase credentials for app push.
Install
Section titled “Install”Add JitPack in settings.gradle.kts:
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:
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:
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />Configure
Section titled “Configure”1. Client, device id, profile id
Section titled “1. Client, device id, profile id”Create the client once in your Application class and register the class in the manifest (android:name=".MyApplication"):
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(""):
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
Section titled “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:
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) } } }}<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
Section titled “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:
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
Section titled “4. Track screens with page tokens”Screen, product, search and checkout views go through one call: build a PushRequest and call relevaClient.push(request).
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
Section titled “5. On-screen content”- Banners:
BannerDisplayManager(client, targetSelector, onLinkTap)thenattach(fragment)orattach(activity).onLinkTapis required; the SDK never navigates for you. - Stories:
StoryDisplayManager.setClient,setOnLinkTap(beforeattach),attach(activity); plus aStoryManagerServiceyouinitialize(response.stories)and drive withonCartChanged(),onWishlistChanged(),onScrollPercentageReached(percentage);dispose()cancels pending timers. - NPS:
NpsDisplayManager.setOnSubmit { token, score, comment -> relevaClient.submitNpsResponse(token, score, comment) }, optionalsetOnSkip, thenattach(this)from aFragmentActivity;relevaClient.trackEvent("checkout_complete")triggers or cancels surveys. - App Inbox: collect
relevaClient.inbox.state(messages,unreadCount,hasMore,isLoading) withrepeatOnLifecycle;refresh(),loadMore(),refreshIfStale()on resume (network only when the cache is older than five minutes);markAsRead,markAllAsRead,deleteMessageupdate the UI immediately and roll back on failure.
Configuration presets: RelevaConfig.full(), trackingOnly(), pushOnly(), or RelevaConfig(enableTracking, enableScreenTracking, enableInAppMessaging, enablePushNotifications, enableAnalytics).
Verify
Section titled “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: the Push Notification Subscribe event is tagged device_android and the profile shows an ANDROID badge.
Troubleshooting
Section titled “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.
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
Section titled “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 |