Skip to main content
📌 Release Notes for August, Week 4: Promotion UI Templates are now available! Building a paywall has never been easier! Learn more

Android SDK

The Monetai Android SDK enables you to integrate dynamic pricing and personalized offers directly into your app. This guide walks you through installation, initialization, event tracking, and implementing dynamic pricing with the SDK.

Prerequisites​

  • Android API Level 21 (Android 5.0) or higher
  • Google Play Billing Library v8 (for SDK version 2.0.0+)
  • Google Play Billing Library v7 (for SDK version 1.x)

Additional Resources​

Language Support​

The Monetai Android SDK supports both Kotlin and Java. Select the appropriate tab below based on your project's language.


SDK Setup​

This section covers how to install the Monetai SDK and configure it to collect the data needed for dynamic pricing.
Please make sure to follow all three steps to lay the foundation for all promotion features.

1. SDK Installation​

Add the Monetai Android SDK to your project using Gradle.

// Add JitPack repository
repositories {
maven { url 'https://jitpack.io' }
}

// Add dependency
dependencies {
implementation 'com.github.hayanmind:monetai-android:2.0.0'
}
Billing Library Version Compatibility

For SDK version 2.0.0 and above:

  • Includes Google Play Billing Library v8 internally
  • Requires Google Play Billing Library v8 or higher

For SDK version 1.x:

  • Includes Google Play Billing Library v7 internally
  • Compatible with Google Play Billing Library v7

Migration from v1.x to v2.0.0:

  • No code changes required for your app
  • Gradle automatically handles dependency resolution
  • Important: If using other billing libraries, ensure they support Billing Library v8

2. SDK Initialization​

Initialize the SDK when your app launches.

import com.monetai.sdk.MonetaiSDK

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

// Initialize Monetai SDK
MonetaiSDK.shared.initialize(
context = this@MainActivity,
sdkKey = "YOUR_SDK_KEY", // SDK key issued from Monetai dashboard
userId = "USER_ID" // User ID of your app's user
) { result, error ->
if (error != null) {
println("Monetai SDK initialization failed: ${error.message}")
} else {
println("Monetai SDK initialization completed: $result")
}
}
}
}

API Reference

Parameters

ParameterTypeDescription
contextContextApplication context
sdkKeystringSDK key issued from Monetai (Settings > SDK Integration)
userIdstringUser ID of your app's user (if not available, use a unique identifier such as email or device ID)
completioncallback?Completion callback called when initialization is complete (optional)

Callback Parameters

ParameterTypeDescription
resultInitializeResult?Result when initialization succeeds
errorException?Error when initialization fails

InitializeResult Type

Return ValueTypeDescription
organizationIdnumberOrganization ID
platform'android'Platform info
versionstringSDK version
userIdstringSet user ID



3. Logging User Events​

This is a critical step. Monetai's AI model relies entirely on the user events you log to analyze behavior and predict purchase intent. Without this data, the prediction feature will not function.

import com.monetai.sdk.MonetaiSDK

// Basic event logging
MonetaiSDK.shared.logEvent("app_in")

// Event logging with parameters
MonetaiSDK.shared.logEvent(
eventName = "screen_in",
params = mapOf("screen" to "home")
)

API Reference

Parameters

ParameterTypeDescription
eventNamestringEvent name
paramsMap<String, Any>?Event parameters (optional)
Event Logging Tips
  • Log all in-app events. Monetai will automatically select events most relevant to non-payer prediction for training.
  • If no events are logged, instrument events on key features or buttons, especially those that occur before a purchase.
Event Handling Before Initialization

Events logged before the SDK is initialized are queued and sent automatically once initialization is complete.

Parameter Usage Guidelines

Important: Even with the same event name, different parameters create different events that the AI model recognizes separately. Using too many diverse parameter values can reduce model accuracy.

Best Practices:

  • Good: { screen: "home" }, { button: "upgrade" }, { category: "premium" }
  • Avoid: { timestamp: "2024-01-15T10:30:00Z" }, { userId: "user123" }, { sessionId: "abc123" }

Why? Parameters like timestamps, user IDs, or session IDs create unique events for each occurrence, making it difficult for the model to find patterns. Focus on parameters that represent user behavior categories rather than specific instances.




Implementing Dynamic Pricing​

With the essential setup complete, this section covers how to record product impressions and retrieve personalized offers.
The core workflow is: define a placement for each screen and log product views → call getOffer() to retrieve personalized offers.

1. Logging Product Views​

This step is required. When a user views a product (pricing screen), call logViewProductItem() to record the impression. This data is essential for Monetai to optimize offer targeting — without it, offer personalization will not work correctly.

Log each product separately

If your pricing screen displays multiple products, you must call logViewProductItem() for each product individually. Every product shown to the user needs its own log call.

All purchase screens​

Define a descriptive placement value for each screen where products are displayed (e.g., main_paywall, special_offer, bottom_banner). This data helps Monetai optimize pricing. When you later create a promotion for a screen, use the same placement value as the promotion's placement so that historical data is automatically linked. If you've already created a promotion in the dashboard, you can find its placement value in Dashboard → Promotions → Promotion Settings.

import com.monetai.sdk.MonetaiSDK
import com.monetai.sdk.models.ViewProductItemParams

// Log when the user sees the pricing screen — call for each product
MonetaiSDK.shared.logViewProductItem(
ViewProductItemParams(
placement = "main_paywall",
productId = "premium_monthly",
price = 9.99,
regularPrice = 9.99,
currencyCode = "USD"
)
)

Pricing optimization screen​

For screens where getOffer() is also used to apply Monetai pricing optimization (see next section), use the same placement value for both logViewProductItem() and getOffer().

// Log when the user sees the pricing screen — call for each product
MonetaiSDK.shared.logViewProductItem(
ViewProductItemParams(
placement = "special_offer",
productId = "premium_monthly",
price = 4.99,
regularPrice = 9.99,
currencyCode = "USD"
)
)

MonetaiSDK.shared.logViewProductItem(
ViewProductItemParams(
placement = "special_offer",
productId = "premium_yearly",
price = 39.99,
regularPrice = 79.99,
currencyCode = "USD"
)
)

API Reference

Parameters (ViewProductItemParams)

ParameterTypeRequiredDescription
placementString✓Identifier for the screen or UI component where the product is displayed (e.g., main_paywall, special_offer, bottom_banner). If you've already created a promotion in the dashboard, you can find the placement value in Dashboard → Promotions → Promotion Settings.
productIdString✓Product ID (store product ID)
priceDouble✓Displayed / discounted price
regularPriceDouble✓Regular price (before discount)
currencyCodeString✓Currency code (e.g., USD, KRW)
monthInt?-Subscription period in months

2. Getting Offers​

Call getOffer(placement) to retrieve a personalized offer for the current user. If the user is eligible for a discount, the SDK returns an Offer object containing the discount details and product information. If not, it returns null.

How to use offers
  • If an offer is returned: Apply the optimized discount rate and product info to your existing pricing or promotion screen.
  • If null is returned: The user belongs to a group where dynamic pricing optimization is not applied. Use your app's existing default discount price.
Avoid redundant offer calls

Each getOffer() call may return a different optimized result for the same user, as the AI model continuously refines its recommendations. If getOffer() is called multiple times while a promotion is active, the discount shown to the user may change unexpectedly.

Example scenario:

  1. User opens the pricing screen → getOffer() returns a 30% discount
  2. User navigates away, then returns → getOffer() is called again → returns a 50% discount
  3. The user sees a different price for the same promotion, causing confusion

Best practice: Call getOffer() once and cache the result while the promotion is active. Do not re-fetch on every screen visit.

Multiple products in a single offer

If your promotion page displays multiple products (e.g., a monthly plan and a yearly plan) and you have registered both in the agent, products will contain an individually optimized result for each product. For example, if you registered a 1-month and a 12-month product, the response will include optimized pricing for both.

import com.monetai.sdk.MonetaiSDK

fun showPricingScreen() {
MonetaiSDK.shared.getOffer(placement = "special_offer") { offer, error ->
if (error != null) {
println("Failed to get offer: ${error.message}")
displayDefaultPrice()
return@getOffer
}

if (offer != null) {
// Offer available — apply discount to your existing UI
// products contains an optimized result per registered product
println("Agent: ${offer.agentName}")
println("Products: ${offer.products}")

offer.products.forEach { product ->
println("SKU: ${product.sku}, Discount: ${product.discountRate * 100}%")
}

displayPrice(offer)
} else {
// No offer — show your app's existing default discount price
displayDefaultPrice()
}
}
}

API Reference

Parameters

ParameterTypeDescription
placementStringUnique identifier for the screen where pricing optimization is applied. Use the same value defined in logViewProductItem(). If a promotion has already been created in the dashboard, you can find the placement value in Dashboard → Promotions → Promotion Settings.

Return Value: Offer | null

Offer Type

PropertyTypeDescription
agentIdIntAgent ID
agentNameStringAgent name
productsList<OfferProduct>List of discounted products

OfferProduct Type

PropertyTypeDescription
nameStringProduct name
skuStringProduct SKU (store product ID)
discountRateDoubleDiscount rate (0-1 range, e.g., 0.5 = 50%)
isManualBooleanWhether the discount is manually set

Managing User State​

SDK Reset​

Initialize the SDK when the user logs out.

import com.monetai.sdk.MonetaiSDK

// When user logs out
fun logoutUser() {
MonetaiSDK.shared.reset()
println("User logout completed")
}

Support
If you run into any trouble during the integration, don't hesitate to contact us at support@monetai.io.


Next Steps​

With the SDK setup complete, you're ready to start a promotion: