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:
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:
| What | Example | Where to find it |
|---|---|---|
| Application ID | com.example.shop | applicationId in app/build.gradle. |
| Firebase project | shop-prod-1234 | Firebase console, Project settings. |
| Permission to send messages | Firebase service-account JSON | Firebase 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
| Step | What you do | Where |
|---|---|---|
| 1 | Install the SDK | app/build.gradle |
| 2 | Start the SDK | Your Application class |
| 3 | Tell AlgorithmX who the customer is | Login, app start, logout |
| 4 | Send events | Where actions happen, such as checkout |
| 5 | Connect push notifications | Your FirebaseMessagingService |
| 6 | Open the right screen | Your navigation code |
| 7 | Check in-app campaigns | No code |
| 8 | Test | A 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:
// app/build.gradle.kts
dependencies {
implementation("cloud.algorithmx:android-sdk:1.1.0")
}
If your project uses Groovy instead:
// 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:
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.
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.
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:
AlgorithmX.setUserProfile(profile)
On logout:
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:
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.
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 ineventType, properties indata, 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
camelCasenaming approach, such asaddToCartandproductId. 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:
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.
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_notificationsand 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.
5c. Forward new intents (recommended)
The SDK handles taps on its own notifications by itself. As a safety net, add one line to onNewIntent of your main Activity:
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 says | What happens | Your code |
|---|---|---|
| Open a screen (deep link) | The SDK gives the link to your handler. | Step 6a |
| Custom action | The SDK gives the action name and its details to your handler. | Step 6b |
| Open a web page | The SDK opens it in the browser. | None |
| Open an in-app campaign | The SDK shows it over your app. | None |
6a. Deep links
Pass the link to the router your app already uses:
import algorithmx.engage.interfaces.DeepLinkHandler
val deepLinkHandler = object : DeepLinkHandler {
override fun onDeepLinkReceived(uri: android.net.Uri): Boolean {
return appNavigator.openDeepLink(uri)
}
}
- Return
trueif your app accepts the link,falseif 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:
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
}
}
}
onNotificationClickruns first on every tap. Returnfalse, so the SDK goes on to run the campaign's action.- The action's details are in
parsedActionData. A number arrives as a number, soas? Stringdoes 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:
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.
- The SDK bootstraps its anonymous profile and device automatically.
- On startup or returning to the foreground, it calls
GET /api/v1/inAppViews?language=...&customerId=.... - The backend checks the customer's segment, campaign publication/schedule and language, and returns eligible inline HTML, CSS, JavaScript, translations and variation parameters.
- 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:
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.
| Method | Endpoint | Purpose |
|---|---|---|
GET | /api/v1/inAppViews | Fetch eligible inline campaigns automatically with language, account/anonymous ID and identity headers. |
POST | /api/v1/Identity/Bootstrap | Create or restore the SDK-generated anonymous profile and device. |
POST | /api/v1/Identity | Link ExternalId and trusted identifiers to the anonymous profile. |
POST | /api/v1/Customer/Ingest | Replace supported customer profile fields. |
POST | /api/v1/Event/Log | Track a custom event or automatic in-app view interaction. |
POST | /api/v1/tracks/algoViewInteract | Track a manual preview or visible-push interaction. |
PUT | /api/v1/inAppPushEvents/device/status | Update notification status. |
POST | /api/v1/notificationTokens | Register 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 AlgorithmX | What 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, setCampaignInteractionListener | Register 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?
| Problem | What to check |
|---|---|
Gradle cannot find cloud.algorithmx:android-sdk | mavenCentral() is in the repositories in settings.gradle, and the version number is right. |
| No events in AlgorithmX | initialize runs in Application.onCreate with the right HTTPS URL and partner ID, and the phone is online. |
| No AlgorithmX notifications | The 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 all | The AlgorithmX check is at the top of onMessageReceived and returns after passing the message on. |
| Tapping a notification does nothing | Your handlers are registered in Application.onCreate and really open a screen. |
| A custom action does nothing | onNotificationClick returns false, and the action name matches exactly. |
| A button opens the wrong screen | Your button handler returned false, so the main action ran. Check the action text. |
| In-app campaign never appears | Your 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 appears | Call 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.
