AlgorithmX
Integrations18 min read

Android Integration

Add AlgorithmX to your Android app step by step: install the SDK, start it, identify customers, send events, connect Firebase push notifications, and open the right screen from campaigns.

SDK 1.1.0: these APIs use SDK-generated anonymous/device IDs and API-based in-app delivery. Existing 1.0.x integrations should follow the updated identity and profile instructions below.

This guide adds the AlgorithmX SDK to your Android app in 8 steps. You keep your app's login, Firebase setup, and navigation. You only add a few lines in places your app already has.

In the examples, names such as appNavigator are your own code, not part of the SDK. Every SDK call goes through AlgorithmX:

kotlin
import algorithmx.engage.core.AlgorithmX

Work through one step at a time with a test customer. First get the app to build, then check one identity and event request. After those work, connect Firebase delivery and try a campaign on the phone. Each step below has a check you can finish before moving on.

Before you start

Check that you have these:

  • An Android app with minSdk 24 or higher, compileSdk 34 or higher, and Java 17.
  • Firebase Cloud Messaging already set up in your app. If you do not have it yet, follow Firebase's Android guide first.
  • The API base URL from AlgorithmX, for example https://api.example.com.
  • Your partner ID from AlgorithmX, for example your-partner-id. The SDK sends it with every SDK API request.
  • The list of customer ID, events, deep links, and custom actions you agreed on with AlgorithmX. See the overview.

Send these to your AlgorithmX contact, so AlgorithmX can send notifications to your app:

WhatExampleWhere to find it
Application IDcom.example.shopapplicationId in app/build.gradle.
Firebase projectshop-prod-1234Firebase console, Project settings.
Permission to send messagesFirebase service-account JSONFirebase console, Project settings → Service accounts → Generate new private key. Upload it in AlgorithmX Settings → In-App Integration. Never put it in the app.

Use Connect Firebase and Send a Test to connect the project in the dashboard. One service-account upload also covers your iOS app when it belongs to that project. The Android app's google-services.json stays in the app and is not the server credential.

The steps

StepWhat you doWhere
1Install the SDKapp/build.gradle
2Start the SDKYour Application class
3Tell AlgorithmX who the customer isLogin, app start, logout
4Send eventsWhere actions happen, such as checkout
5Connect push notificationsYour FirebaseMessagingService
6Open the right screenYour navigation code
7Check in-app campaignsNo code
8TestA real phone

Step 1: Install the SDK

This step makes the library available to your app. Finish the build check before adding customer or push code, so a dependency problem is easy to isolate.

Add the SDK to the dependencies block of your app module:

kotlin
// app/build.gradle.kts
dependencies {
    implementation("cloud.algorithmx:android-sdk:1.1.0")
}

If your project uses Groovy instead:

groovy
// app/build.gradle
dependencies {
    implementation 'cloud.algorithmx:android-sdk:1.1.0'
}

The SDK comes from Maven Central. New Android projects already include it. If yours does not, add mavenCentral() in settings.gradle:

kotlin
dependencyResolutionManagement {
    repositories {
        google()
        mavenCentral()
    }
}

Check: Gradle sync finishes without errors.

Good to know:

  • The SDK brings everything it needs (OkHttp, Gson, coroutines, AndroidX). It does not include Firebase; your app keeps its own.
  • Release builds with R8/ProGuard need no extra rules.
  • To update later, change the version number. See the changelog.

Step 2: Start the SDK

Add these lines to onCreate of your Application class. Keep your existing code.

kotlin
class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        // Keep your existing startup code.

        AlgorithmX.initialize(this, "https://api.example.com", "your-partner-id")
        AlgorithmX.setLoggingEnabled(BuildConfig.DEBUG)
        AlgorithmX.setSmallIcon(R.drawable.ic_stat_notification) // Your notification icon.

        // Your handlers from step 6:
        AlgorithmX.setDeepLinkHandler(deepLinkHandler)
        AlgorithmX.setNotificationClickListener(notificationClickListener)
        AlgorithmX.setActionButtonHandler(actionButtonHandler)
    }
}

Why in Application and not in an Activity? Firebase can wake your app in the background to deliver a message. No screen opens then, but Application.onCreate still runs. SDK calls made before initialize are ignored.

  • Notification icon: without setSmallIcon, AlgorithmX notifications show a plain Android icon.
  • Handlers: the SDK keeps them while the app runs. Let them call your navigation code; do not keep an Activity inside them.

Check: run a debug build. Logcat shows lines with the tag AlgorithmX.

Step 3: Tell AlgorithmX who the customer is

The SDK generates and stores an anonymous UUID and a separate installation device UUID during startup. You do not generate either ID or call the bootstrap endpoint yourself. The anonymous UUID stays the same across app restarts and login; events continue to use it in X-Anonymous-Id.

Use the stable account ID from your application's backend when the customer signs in. The SDK sends it as ExternalId, allowing AlgorithmX to resolve the same customer across devices. AlgorithmX manages its own internal profile ID.

Call the identity function after login and when starting with a signed-in customer. Email and phone become trusted identifiers; supported profile fields are sent separately to /Customer/Ingest.

kotlin
AlgorithmX.identifyUser("customer_123", mapOf(
    "email" to "[email protected]",
    "firstName" to "Amina", "lastName" to "Hassan",
    "emailOptIn" to true, "smsOptIn" to false, "pushOptIn" to true,
    "gdprAccepted" to true, "whatsAppOptIn" to false
))

Supported identifier fields are email, phone, and userName; your application's userId becomes ExternalId. Supported profile fields are firstName, lastName, gender, dateOfBirth, registeredAt, emailOptIn, smsOptIn, pushOptIn, gdprAccepted, and whatsAppOptIn. Send dates as ISO 8601 text and consent fields as booleans.

Send a complete profile. /Customer/Ingest replaces these traits: omitted text/date fields are cleared and omitted consent fields become false. Include all current values whenever you send profile fields through identify / identifyUser or setUserProfile. An identify call containing only identifiers does not send a profile update.

Fields such as plan, language, country, and loyaltyTier are not supported customer traits by these endpoints. The SDK rejects unsupported fields. Send arbitrary business data with trackEvent; that records event data and does not create custom profile fields.

To update profile fields later, pass profile, your application's complete current customer profile object, without email, phone, or userName:

kotlin
AlgorithmX.setUserProfile(profile)

On logout:

kotlin
AlgorithmX.resetIdentity()

Logout clears waiting campaigns, generates a fresh anonymous UUID and bootstraps a new anonymous profile. The installation's device UUID is retained. Calling identify with a different account ID also rotates the anonymous UUID first, preventing the two accounts from being merged. Close any campaign already on screen as part of your app's logout flow.

To inspect the SDK-generated UUID for diagnostics:

kotlin
val anonymousId = AlgorithmX.getAnonymousId()

The SDK remembers the external account ID across restarts. These calls do not replace your application's authentication. API requests are sent in order, but the backend responds with 202 Accepted and processes messages asynchronously; confirm the stored customer data in AlgorithmX. Offline event/profile requests are dropped. Bootstrap and saved account identification are attempted again on startup/foreground; profile updates must be sent again by your app if delivery failed.

Check: the customer can be found using the external ID/email you supplied, and the anonymous UUID is unchanged after login. After logout or switching accounts, it changes.

Step 4: Send events

Choose one action you can easily repeat while testing, such as opening a product. Confirm its event arrives before adding all your business events. The campaign team will use these names and details, so agree on them together.

Send an event right after an action succeeds, for example after an order is confirmed. Put it next to your existing analytics calls.

kotlin
AlgorithmX.trackEvent("productView", mapOf("productId" to "SKU-123"))

AlgorithmX.trackEvent("addToCart", mapOf("productId" to "SKU-123", "quantity" to 2))

AlgorithmX.trackEvent("purchase", mapOf(
    "orderId" to "ORDER-1001",
    "total" to 149.90,
    "currency" to "SAR",
    "items" to listOf(mapOf("productId" to "SKU-123", "quantity" to 2))
))

Rules for events:

  • Event transport: general events use POST /api/v1/Event/Log, with the event name in eventType, properties in data, and an ISO 8601 UTC timestamp. The SDK sends an array and adds the required partner and anonymous-ID headers automatically. See the request contract.

  • Values: use text, numbers, true/false, and lists or maps of these.

  • Names and keys: use AlgorithmX's camelCase naming approach, such as addToCart and productId. Custom names and keys are sent as supplied; their casing is not enforced or normalized.

  • Offline: an event sent without internet is lost. It is not sent again later. Keep your own backend as the record of orders and payments.

  • Past data: only new events are sent. To bring in older data, ask your AlgorithmX contact about a data import.

Check: the event appears for the customer in AlgorithmX.

Step 5: Connect push notifications

This step gives AlgorithmX the phone's push address and a way to process its messages. Treat token registration and message delivery as separate checks: receiving a token does not by itself prove that a push can reach the app.

You keep your Firebase project and your messaging service. You add three things to them.

5a. Send the push token on every app start

In Application.onCreate, after step 2:

kotlin
import com.google.firebase.messaging.FirebaseMessaging

FirebaseMessaging.getInstance().token.addOnSuccessListener { token ->
    AlgorithmX.registerDeviceToken(token)
    // Keep your own token registration here too.
}

Why every start? Customers who update your app already have a token. AlgorithmX has not seen it yet, and Firebase does not send a new one just because you added the SDK. If your code skips sending an unchanged token, do not skip this call.

5b. Pass AlgorithmX messages to the SDK

In your existing FirebaseMessagingService, add the AlgorithmX check at the top of onMessageReceived, and send new tokens in onNewToken. Do not create a second service.

kotlin
override fun onMessageReceived(message: RemoteMessage) {
    super.onMessageReceived(message)

    if (AlgorithmX.isAlgorithmXPush(message.data)) {
        AlgorithmX.handleFcmMessage(
            applicationContext,
            message.data,
            message.notification?.title,
            message.notification?.body
        )
        return // Stop here. The SDK shows this notification.
    }

    // Your existing code for other messages stays here.
}

override fun onNewToken(token: String) {
    super.onNewToken(token)
    AlgorithmX.registerDeviceToken(token)
    // Keep your own token registration here too.
}

Important: the check must come before your own notification code, and it must return. The SDK builds AlgorithmX notifications itself, with image and buttons. If your code handles them too, customers see the notification twice.

Good to know:

  • The SDK uses the notification channel algorithmx_notifications and your app's notification permission. Keep your own permission prompt; the SDK never asks for permission.
  • AlgorithmX notification IDs start at 10000. If your app uses IDs in that range, tell your AlgorithmX contact.

The SDK handles taps on its own notifications by itself. As a safety net, add one line to onNewIntent of your main Activity:

kotlin
override fun onNewIntent(intent: android.content.Intent) {
    super.onNewIntent(intent)
    setIntent(intent)
    AlgorithmX.handleNewIntent(this, intent)
    // Keep your existing code here.
}

Check: ask your campaign team to send a test notification. It appears once, with its image and buttons.

Step 6: Open the right screen when a customer taps

Think of a campaign action as a destination request. The SDK tells your app where the customer wants to go, and your existing router decides how to open that screen. Agree on the supported destinations before your campaign team uses them.

A campaign can do one of four things when the customer taps it. Two of them need your code:

The campaign saysWhat happensYour code
Open a screen (deep link)The SDK gives the link to your handler.Step 6a
Custom actionThe SDK gives the action name and its details to your handler.Step 6b
Open a web pageThe SDK opens it in the browser.None
Open an in-app campaignThe SDK shows it over your app.None

Pass the link to the router your app already uses:

kotlin
import algorithmx.engage.interfaces.DeepLinkHandler

val deepLinkHandler = object : DeepLinkHandler {
    override fun onDeepLinkReceived(uri: android.net.Uri): Boolean {
        return appNavigator.openDeepLink(uri)
    }
}
  • Return true if your app accepts the link, false if not.
  • The SDK never opens the link by itself. If you set no handler, nothing happens.
  • This can run before any screen is open, for example when a tap starts the app. Start screens with FLAG_ACTIVITY_NEW_TASK, or let your router wait until the app is ready.
  • You do not need new links or screens. Give your campaign team the links your app already supports, for example myapp://open/product?id=SKU-123.

6b. Custom actions

Map each action name you agreed on to a screen:

kotlin
import algorithmx.engage.interfaces.NotificationClickListener

val notificationClickListener = object : NotificationClickListener {
    // Return false so the SDK runs the campaign's action.
    override fun onNotificationClick(data: Map<String, Any>): Boolean = false

    override fun onCustomAction(action: String?, data: Map<String, Any>): Boolean {
        val details = data["parsedActionData"] as? Map<*, *> ?: return false
        return when (action) {
            "viewProduct" -> {
                val productId = (details["productId"] as? String)
                    ?.takeIf { it.isNotBlank() } ?: return false
                appNavigator.openProduct(productId)
            }
            "viewCart" -> appNavigator.openCart()
            else -> false
        }
    }
}
  • onNotificationClick runs first on every tap. Return false, so the SDK goes on to run the campaign's action.
  • The action's details are in parsedActionData. A number arrives as a number, so as? String does not work for it. Agree on the types with your campaign team.
  • An action name your app does not know does nothing. Only offer actions that your released app supports.

6c. Notification buttons

A notification can have up to three buttons. Match on the button's action text, not on its title, because the title can be translated:

kotlin
import algorithmx.engage.interfaces.ActionButtonHandler

val actionButtonHandler = object : ActionButtonHandler {
    override fun onActionButtonClicked(
        buttonId: String,
        actionText: String,
        title: String,
        notificationData: Map<String, Any>
    ): Boolean = when (actionText) {
        "viewCart" -> appNavigator.openCart()
        "dismiss" -> true // Handled: do nothing more.
        else -> false
    }
}

Every button opens the app. Return true when you handled the button. If you return false, the SDK runs the notification's main action instead.

Register all three handlers in step 2. Keep your normal login and permission checks before sensitive screens: a campaign only suggests where to go.

Check: send a test notification for each link, action, and button your app supports. The right screen opens once.

Step 7: Check in-app campaigns

Production backend support is pending: the .NET in-app delivery route must be implemented as described in AlgorithmX issue #207. Current device tests use in-app-test-backend; no .NET implementation is included in this SDK update.

In-app campaigns use the API in SDK 1.1.0. Initialise the SDK and identify a signed-in customer; no campaign-fetch code, silent push, push token, or notification permission is needed for this flow.

  1. The SDK bootstraps its anonymous profile and device automatically.
  2. On startup or returning to the foreground, it calls GET /api/v1/inAppViews?language=...&customerId=....
  3. The backend checks the customer's segment, campaign publication/schedule and language, and returns eligible inline HTML, CSS, JavaScript, translations and variation parameters.
  4. The SDK selects a stable variation, applies priority, frequency, expiry and app-enter delay, and displays at most one campaign per visit. The template supplies its close button; Android also supports Back.

The SDK supplies X-Partner-Id, its persistent UUID in X-Anonymous-Id, and the installation UUID in X-Device-Id. Before login, customerId is the anonymous UUID. After identify / identifyUser, it is your application's account ID, stored by AlgorithmX as ExternalId. The backend resolves the internal profile ID; your app does not pass an AlgorithmX profile UUID. Identification, logout and account changes invalidate old campaign requests and content. Signed-in variation selection and local display history use the account ID.

Language defaults to the device/app language. Override it only when your app has its own language selector:

kotlin
AlgorithmX.setInAppLanguage("ar")

An empty language override restores the automatic default. Arabic, Hebrew, Persian and Urdu translations use RTL layout; text and placeholder translations are applied from the template's builderState.translations.

First check: publish an active campaign that matches your test customer's segment and language, open the app, and confirm the GET request and impression. Leave the app and return to check another visit. Impressions, clicks, submits, copies and closes are logged through POST /api/v1/Event/Log as inAppViewInteraction; campaign and variation UUIDs remain strings.

The automatic mobile flow supports app-enter campaigns and an optional time delay. Browser URL/scroll/exit/inactivity rules and custom triggers are excluded by the backend from this automatic feed. Display history is stored on the installation; this is not a global cross-device frequency counter.

GET requests follow queued identity/profile POSTs. When identity is still processing (409), the SDK retries up to three times, and it retries again when connectivity returns or the app re-enters the foreground. Normal event/profile requests remain fire-and-forget. The old silent-push algoTriggerWebview is ignored. Visible push notifications retain their separate integration.

Step 8: Test before you release

Keep a test customer and the campaign team ready for this final pass. Check both what the person sees on the phone and what AlgorithmX records. Testing only the screen or only the server leaves half of the journey unchecked.

Use a real phone and a test customer. Test a debug build and your release build.

  • Update while logged in: install your current store version, log in, then update to the new build. The customer is recognized without logging in again.
  • Login, restart, logout, second account: events use the right customer each time. No campaign from the first account appears for the second.
  • Your existing notifications still work exactly as before.
  • AlgorithmX notification with the app open, in the background, and closed: it appears once, and a tap opens the right screen once.
  • Each deep link, custom action, and button opens the right screen.
  • In-app campaign: the SDK fetches it and it appears when the app opens and closes with its close button or Back.
  • Notifications turned off: in-app campaigns still arrive.
  • Release build: notifications, taps, and campaign buttons still work.
  • Events appear for the customer in AlgorithmX.

While testing, Logcat shows each SDK request under the AlgorithmX tag.

SDK endpoints

You do not need to write HTTP calls for these endpoints in your app; the SDK sends them when you use its APIs. This reference helps you or your backend team inspect requests during testing.

These paths are relative to your configured apiBaseUrl. SDK API requests include the x-partner-id header.

MethodEndpointPurpose
GET/api/v1/inAppViewsFetch eligible inline campaigns automatically with language, account/anonymous ID and identity headers.
POST/api/v1/Identity/BootstrapCreate or restore the SDK-generated anonymous profile and device.
POST/api/v1/IdentityLink ExternalId and trusted identifiers to the anonymous profile.
POST/api/v1/Customer/IngestReplace supported customer profile fields.
POST/api/v1/Event/LogTrack a custom event or automatic in-app view interaction.
POST/api/v1/tracks/algoViewInteractTrack a manual preview or visible-push interaction.
PUT/api/v1/inAppPushEvents/device/statusUpdate notification status.
POST/api/v1/notificationTokensRegister a push token.

trackEvent posts a one-event array to /api/v1/Event/Log: [{ eventType, data, timestamp }]. data contains the supplied properties or {}; timestamp is ISO 8601 UTC. In SDK 1.1.0, X-Anonymous-Id always contains the SDK-generated anonymous UUID, including after login. Identity requests use anonymousId and trustedIdentifiers, not fingerprintDevice, previousFingerprintDevice, or an attributes object on the wire. The SDK separates profile fields into /Customer/Ingest and adds X-Anonymous-Id and X-Device-Id to that request. All requests include X-Partner-Id.

API-based in-app view interactions use /api/v1/Event/Log with eventType: "inAppViewInteraction". Manual previews, visible-push interactions, token registration and notification status retain their existing transport contracts and need separate backend endpoint support. API templates are inline; manual preview HTML and notification images use GET requests to supplied URLs.

For a custom backend route, trackCampaignInteraction(..., endpoint = ...) can override the campaign interaction endpoint.

Quick reference

Call on AlgorithmXWhat it does
initialize(application, apiBaseUrl, partnerId)Starts the SDK. Call it in Application.onCreate.
setLoggingEnabled(enabled)Shows SDK requests in Logcat. Off by default.
setSmallIcon(resId)Sets the icon of AlgorithmX notifications.
setUserProfile(profile)Replace supported customer fields with the complete current profile.
setInAppLanguage(language)Optional override of automatic device/app language.
getAnonymousId()Read the SDK-generated anonymous UUID.
identifyUser(userId, attributes)Sets the customer. Call at login and app start.
resetIdentity()Goes back to an anonymous customer. Call at logout.
trackEvent(name, properties)Sends an event.
registerDeviceToken(token)Sends the push token. Call on every app start and in onNewToken.
isAlgorithmXPush(data)Tells you if a Firebase message is from AlgorithmX.
handleFcmMessage(context, data, title, body)Gives an AlgorithmX message to the SDK.
handleNewIntent(activity, intent)Gives a new intent to the SDK.
setDeepLinkHandler, setNotificationClickListener, setActionButtonHandler, setCampaignInteractionListenerRegister your handlers. Each has a matching remove call.
clearWebViewQueue()Removes waiting in-app campaigns. Call at logout.
getDeviceFingerprint(), getQueueSize()Show the current customer ID and waiting campaigns, for testing.

Something not working?

ProblemWhat to check
Gradle cannot find cloud.algorithmx:android-sdkmavenCentral() is in the repositories in settings.gradle, and the version number is right.
No events in AlgorithmXinitialize runs in Application.onCreate with the right HTTPS URL and partner ID, and the phone is online.
No AlgorithmX notificationsThe token is sent on every app start (5a). AlgorithmX has permission to send through your Firebase project. Your service passes AlgorithmX messages to the SDK (5b). Notifications are allowed for the app.
Notifications appear twice, or not at allThe AlgorithmX check is at the top of onMessageReceived and returns after passing the message on.
Tapping a notification does nothingYour handlers are registered in Application.onCreate and really open a screen.
A custom action does nothingonNotificationClick returns false, and the action name matches exactly.
A button opens the wrong screenYour button handler returned false, so the main action ran. Check the action text.
In-app campaign never appearsYour service passes the message to the SDK, the app was not force-stopped, and you opened the app again after the campaign was sent.
A previous account's campaign appearsCall clearWebViewQueue() at logout and when switching accounts.

Next steps

Create your first campaigns with In-App Push Campaigns and In-App View Campaigns. Go back to the overview for other platforms.