Android SDK Reference
CohortSDK is an Android library designed to easily integrate your Android applications with the Cohort.ai backend. It provides a native, type-safe interface to fetch dynamically generated, AI-targeted paywall campaigns and track user sessions for cohort routing.
Requirements
- Android API Level 21+
- Kotlin 1.9+
Installation
1. Install from GitHub Packages (Private)
Since this SDK is hosted in a private GitHub Packages registry, you must provide a Personal Access Token (PAT) with read:packages scope to install it.
Add the Repository
In your settings.gradle (or settings.gradle.kts), add the GitHub Packages Maven repository:
dependencyResolutionManagement {
repositories {
google()
mavenCentral()
maven {
url = uri("https://maven.pkg.github.com/tay-ola/Cohort.ai")
credentials {
username = "YOUR_GITHUB_USERNAME"
password = "YOUR_GITHUB_PAT" // Token with read:packages scope
}
}
}
} Add the Dependency
Add the dependency to your app's build.gradle:
dependencies {
implementation 'ai.cohort:sdk-android:1.0.0'
} 2. Adding as a Local Module (Alternative)
If you prefer not to use the remote package, you can still add it as a local module:
- Clone the Repository: Ensure this entire private repository is cloned to your local machine.
- Open your Android Project: Open your main Android app in Android Studio.
- Import Module: Go to
File > New > Import Module...and select theCohortSDK-Androiddirectory. - Add Dependency: Open your app's
build.gradlefile and add the following line to your dependencies block:implementation project(':CohortSDK-Android')
Initialize the SDK
Before making any requests, you must initialize the SDK. The easiest way is to download the cohort-config.json file from your Cohort Dashboard and place it in your android/app/src/main/assets/ directory.
Then, initialize the SDK once, typically in your custom Application class:
import ai.cohort.sdk.CohortSDK
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
CohortSDK.initialize(
userId = "user_12345", // Optional: Identify the user immediately
context = this // Passing context is required to read assets and enables silent background billing history sync
)
}
} Track User Activity
To ensure users are placed in the correct cohort (e.g., new_user, high_intent), you should track user sessions and paywall views.
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
// Track a general session start
GlobalScope.launch {
try {
CohortSDK.trackActivity(
eventType = "session_start"
)
} catch (e: Exception) {
// Handle error
}
}
// Track when a user views a paywall
GlobalScope.launch {
try {
CohortSDK.trackActivity(
eventType = "paywall_view"
)
} catch (e: Exception) {
// Handle error
}
} Track your "North Star" Metric (Success Goal)
Cohort.ai optimizes your marketing copy based on a Success Goal. By default, this is purchase_success, but you can customize this in the Dashboard Settings (e.g., to _core_event, lesson_completed, etc.).
To drive AI optimization, track your custom success event whenever the user achieves it:
GlobalScope.launch {
try {
CohortSDK.trackActivity(
eventType = "_core_event" // Matches the Success Event ID in your Dashboard
)
} catch (e: Exception) {
// Handle error
}
} Advanced Tracking (FCM & Receipts)
To link Android app purchases and subscriptions with backend webhooks (which parse the Google Play Pub/Sub notifications), you must track the successful purchase. You can do this easily by passing the Google Play Billing Library Purchase object directly to trackPurchase:
Google User ID Equivalent (obfuscatedAccountId)
On iOS StoreKit 2, developers set the appAccountToken to identify which app user initiated a transaction. The equivalent in Google Play Billing is the Obfuscated Account ID.
- When launching the purchase flow, configure the user ID using
.setObfuscatedAccountId(userId)inBillingFlowParams. - Note: Google Play Pub/Sub billing notifications do not directly include the obfuscated account ID. Therefore, you must invoke
trackPurchaseon the device upon purchase success to map your app'suserIdwith thepurchaseTokenstored in D1.
// Example: Tracking a Google Play Billing Library purchase success using the native helper wrapper
GlobalScope.launch {
try {
CohortSDK.trackPurchase(
purchase = purchase, // Passes the Purchase object directly
fcmToken = "e123abc-xyz-token" // Store their FCM push token (optional)
)
} catch (e: Exception) {
// Handle error
}
} Behind the scenes, this automatically extracts the purchase.purchaseToken and maps it to the originalTransactionId parameter to link backend webhook updates.
Fetch a Campaign
Call the getCampaignConfig method to retrieve the localized marketing copy and discount eligibility for a user.
Kotlin (Coroutine):
viewModelScope.launch {
try {
val campaign = CohortSDK.getCampaignConfig()
// Use campaign
} catch (e: Exception) {
// Handle error
}
} Java (Callback):
CohortSDK.getCampaignConfigAsync(null, new CohortSDK.CampaignCallback() {
@Override
public void onSuccess(@NonNull CampaignResponse campaign) {
// Use campaign
}
@Override
public void onFailure(@NonNull Exception e) {
// Handle error
}
}); SDK Debugger (Production Safe)
CohortSDK includes a built-in debug menu to inspect the current User ID, App ID, and SDK state on real devices.
Usage
In your Activity or Fragment (Debug builds only):
CohortSDK.showDebugUI(this) Production Safety
This feature is automatically disabled in release builds. The SDK internally checks the FLAG_DEBUGGABLE manifest flag. If called in a production build, the function will simply log a warning and return, ensuring no sensitive internals are exposed to end-users.
Handling Paywall Push Notifications
Cohort.ai can trigger automated push notifications targeting specific user cohorts. When users tap these notifications, you should route them directly to your app's paywall.
1. Payload Structure
Cohort push notifications include a custom payload with the following key-value pair in the data block of the FCM message:
- Key:
"action" - Value:
"open_paywall"
2. Implementation & Integration Checklist
To route users correctly when they tap a notification, check the launcher intent extras in your main activity:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
handleIntent(intent)
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
handleIntent(intent)
}
private fun handleIntent(intent: Intent?) {
val action = intent?.getStringExtra("action")
if (action == "open_paywall") {
// Navigate to your Paywall Activity or Screen
val paywallIntent = Intent(this, PaywallActivity::class.java)
startActivity(paywallIntent)
}
} 3. Key Considerations & Things to Watch Out For
Important
Handle onNewIntent for Warm Starts: If your launcher activity has a launch mode of singleTop or singleTask, tapping a push notification while the app is in the background will route the intent to onNewIntent rather than onCreate. You must handle the check in both callbacks.
Warning
Check SDK Initialization Timing: Do not attempt to query CohortSDK.getCampaignConfig() until CohortSDK.initialize() has run (typically in your Application class). Attempting to fetch configs before initialization will result in a runtime exception.
Note
Dismiss Active Overlays: Ensure any blocker dialogs, onboarding overlays, or loader dialogs are dismissed/cleared before launching the paywall screen to ensure a smooth layout transition.
Architecture Notes
- The SDK utilizes Kotlin Coroutines (
suspendfunctions executing onDispatchers.IO) for network requests. - Relies on OkHttp for networking and Gson for JSON serialization/deserialization.
- All requests are sent to
/v1/campaignsand/v1/activities. - Automatically includes the
x-sdk-versionheader in all requests. - Response models map JSON
snake_casekeys (likecohort_idandvariant_id) to Kotlin's standardcamelCase.