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​
- GitHub Repository: https://github.com/hayanmind/monetai-android
- Example Apps: Check out various integration examples in the
examplesfolder of the GitHub repository
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'
}
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.
- Kotlin
- Java
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
| Parameter | Type | Description |
|---|---|---|
| context | Context | Application context |
| sdkKey | string | SDK key issued from Monetai (Settings > SDK Integration) |
| userId | string | User ID of your app's user (if not available, use a unique identifier such as email or device ID) |
| completion | callback? | Completion callback called when initialization is complete (optional) |
Callback Parameters
| Parameter | Type | Description |
|---|---|---|
| result | InitializeResult? | Result when initialization succeeds |
| error | Exception? | Error when initialization fails |
InitializeResult Type
| Return Value | Type | Description |
|---|---|---|
| organizationId | number | Organization ID |
| platform | 'android' | Platform info |
| version | string | SDK version |
| userId | string | Set user ID |
import com.monetai.sdk.MonetaiSDKJava;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize Monetai SDK
MonetaiSDKJava.getShared().initialize(
this, // Application context
"YOUR_SDK_KEY", // SDK key issued from Monetai dashboard
"USER_ID", // User ID of your app's user
(result, error) -> {
if (error != null) {
Log.e("MonetaiSDK", "Initialization failed: " + error.getMessage());
} else {
Log.d("MonetaiSDK", "Initialization completed: " + result);
}
}
);
}
}
API Reference
Parameters
| Parameter | Type | Description |
|---|---|---|
| context | Context | Application context |
| sdkKey | string | SDK key issued from Monetai (Settings > SDK Integration) |
| userId | string | User ID of your app's user |
| completion | callback? | Completion callback called when initialization is complete (optional) |
Callback Parameters
| Parameter | Type | Description |
|---|---|---|
| result | InitializeResult? | Result when initialization succeeds |
| error | Exception? | Error when initialization fails |
InitializeResult Type
| Return Value | Type | Description |
|---|---|---|
| organizationId | number | Organization ID |
| platform | 'android' | Platform info |
| version | string | SDK version |
| userId | string | Set 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.
- Kotlin
- Java
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
| Parameter | Type | Description |
|---|---|---|
| eventName | string | Event name |
| params | Map<String, Any>? | Event parameters (optional) |
import com.monetai.sdk.MonetaiSDKJava;
// Basic event logging
MonetaiSDKJava.getShared().logEvent("app_in");
// Event logging with parameters
Map<String, Object> params = new HashMap<>();
params.put("screen", "home");
MonetaiSDKJava.getShared().logEvent("screen_in", params);
API Reference
Parameters
| Parameter | Type | Description |
|---|---|---|
| eventName | string | Event name |
| params | Map<String, Any>? | Event parameters (optional) |
- 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.
Events logged before the SDK is initialized are queued and sent automatically once initialization is complete.
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 aplacementfor each screen and log product views → callgetOffer()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.
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.
- Kotlin
- Java
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"
)
)
import com.monetai.sdk.MonetaiSDKJava;
import com.monetai.sdk.models.ViewProductItemParams;
// Log when the user sees the pricing screen — call for each product
MonetaiSDKJava.getShared().logViewProductItem(
new ViewProductItemParams(
"main_paywall", // placement
"premium_monthly", // productId
9.99, // price
9.99, // regularPrice
"USD" // currencyCode
)
);
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().
- Kotlin
- Java
// 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"
)
)
// Log when the user sees the pricing screen — call for each product
MonetaiSDKJava.getShared().logViewProductItem(
new ViewProductItemParams(
"special_offer", // placement
"premium_monthly", // productId
4.99, // price
9.99, // regularPrice
"USD" // currencyCode
)
);
MonetaiSDKJava.getShared().logViewProductItem(
new ViewProductItemParams(
"special_offer", // placement
"premium_yearly", // productId
39.99, // price
79.99, // regularPrice
"USD" // currencyCode
)
);
API Reference
Parameters (ViewProductItemParams)
| Parameter | Type | Required | Description |
|---|---|---|---|
| placement | String | ✓ | 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. |
| productId | String | ✓ | Product ID (store product ID) |
| price | Double | ✓ | Displayed / discounted price |
| regularPrice | Double | ✓ | Regular price (before discount) |
| currencyCode | String | ✓ | Currency code (e.g., USD, KRW) |
| month | Int? | - | 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.
- If an offer is returned: Apply the optimized discount rate and product info to your existing pricing or promotion screen.
- If
nullis returned: The user belongs to a group where dynamic pricing optimization is not applied. Use your app's existing default discount price.
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:
- User opens the pricing screen →
getOffer()returns a 30% discount - User navigates away, then returns →
getOffer()is called again → returns a 50% discount - 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.
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.
- Kotlin
- Java
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()
}
}
}
import com.monetai.sdk.MonetaiSDKJava;
private void showPricingScreen() {
MonetaiSDKJava.getShared().getOffer("special_offer", (offer, error) -> {
if (error != null) {
Log.e("MonetaiSDK", "Failed to get offer: " + error.getMessage());
displayDefaultPrice();
return;
}
if (offer != null) {
// Offer available — apply discount to your existing UI
// products contains an optimized result per registered product
Log.d("MonetaiSDK", "Agent: " + offer.getAgentName());
Log.d("MonetaiSDK", "Products: " + offer.getProducts());
for (OfferProduct product : offer.getProducts()) {
Log.d("MonetaiSDK", "SKU: " + product.getSku() +
", Discount: " + (product.getDiscountRate() * 100) + "%");
}
displayPrice(offer);
} else {
// No offer — show your app's existing default discount price
displayDefaultPrice();
}
});
}
API Reference
Parameters
| Parameter | Type | Description |
|---|---|---|
| placement | String | Unique 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
| Property | Type | Description |
|---|---|---|
| agentId | Int | Agent ID |
| agentName | String | Agent name |
| products | List<OfferProduct> | List of discounted products |
OfferProduct Type
| Property | Type | Description |
|---|---|---|
| name | String | Product name |
| sku | String | Product SKU (store product ID) |
| discountRate | Double | Discount rate (0-1 range, e.g., 0.5 = 50%) |
| isManual | Boolean | Whether the discount is manually set |
Managing User State​
SDK Reset​
Initialize the SDK when the user logs out.
- Kotlin
- Java
import com.monetai.sdk.MonetaiSDK
// When user logs out
fun logoutUser() {
MonetaiSDK.shared.reset()
println("User logout completed")
}
import com.monetai.sdk.MonetaiSDKJava;
// When user logs out
private void logoutUser() {
MonetaiSDKJava.getShared().reset();
Log.d("MonetaiSDK", "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: