Android SDK
The MonetizationOS Android SDK lets a native app call MonetizationOS directly with a public key. It requests a surface decision for the item a user opens, answers access and meter questions from the features in the response, shows native or web paywalls, and keeps working offline from a decision cache and a queue of unsent meter updates.
To call the Surface Decision API yourself without the SDK, follow the Android recipe instead.
Prerequisites
- A MonetizationOS environment with a configured surface and a feature for the app to check.
- A public key. In the console, open your environment's API Keys screen and select New Public Key under Public Keys. The SDK refuses any key that doesn't start with
pk_, because a secret key must never ship in an app. - An Android app with
minSdk28 or higher andcompileSdk36 or higher, built with Kotlin 2.3 or later. Every SDK call is a Kotlin suspend function, so call it from a coroutine. Java callers aren't supported.
Install
Add mavenCentral() to your repositories, then add the dependency:
dependencyResolutionManagement {
repositories {
google()
mavenCentral()
}
}dependencies {
implementation("com.monetizationos:mos-android:0.9.0")
}The library's manifest declares the INTERNET permission, so there's nothing to add to yours.
mos-android brings in mos-core, kotlinx-serialization-json, and kotlinx-coroutines-core as API dependencies. The SDK is pre-1.0, and a minor release can include breaking changes, so pin the version and read the changelog before you upgrade. Failure reasons, redemption actions, experience kinds, property types, and decision sources can gain cases in a minor release, so give each when over them an else branch.
Quick start
Create one MOS client per process, in Application.onCreate rather than in an Activity, and keep it for the life of the app. Clients with keys for the same environment use the same cache.json, queue.json, and meters.json files, so two of them overwrite each other's entries.
import com.monetizationos.sdk.AppInfo
import com.monetizationos.sdk.MOS
import com.monetizationos.sdk.MOSConfig
import com.monetizationos.sdk.android.create
import com.monetizationos.sdk.android.from
class ExampleApp : Application() {
lateinit var mos: MOS
private set
override fun onCreate() {
super.onCreate()
mos = MOS.create(
this,
MOSConfig(
publicKey = "pk_live_...",
surface = "mobile-app",
app = AppInfo.from(this),
),
)
}
}Register the class as android:name on your manifest's <application> element.
MOS.create applies the Android defaults. It keeps the anonymous identifier in private SharedPreferences, puts the cache, the queue, and the meter counts under noBackupFilesDir, and builds the User-Agent from android.os.Build. It does no disk I/O on the calling thread, so it's safe in Application.onCreate under StrictMode. Construction throws IllegalArgumentException for a key that isn't public.
surface is the slug of the surface the app uses by default. AppInfo.from(context) reads your app's label and versionName, which the SDK sends in the User-Agent header so that app traffic is distinguishable from web traffic in observability. A blank name or version is sent as app.
While you integrate, pass onLog = consoleLogger (from com.monetizationos.sdk.logging) to MOSConfig to print each request, cache hit, and failure.
Run a decision for the item the user is looking at, then check access:
import com.monetizationos.sdk.Resource
val result = mos.decide(Resource(id = "article/123", meta = mapOf("section" to "sport")))
if (result.hasAccess(feature = "article", property = "enabled")) {
// Show the article.
} else {
// Show a paywall.
}Resource.id identifies the item. A meter set to Unique Resources counts each distinct id once. meta is a map of strings that your workflows can read.
hasAccess(feature, property) returns a meterable property's hasAccess, or a boolean property's value. With no decision, a missing property, a boolean property that has no value, or a property of another type, it returns the failOpen setting described under Offline and metering.
decide doesn't throw. Failures come back in the result as result.failure, and result.source says where the decision came from. The only exception any SDK call throws is CancellationException, when the calling coroutine is cancelled. A decision consumes the meters it counts against, so decide once per item the user opens and reuse the result for every check. The SDK never retries a decision, because a retry could consume a second unit, and identical decisions already in flight share one request.
To use a different surface for one call, pass surface =. To send extra context to your workflows, pass properties = as a JsonObject, which workflows read as context.properties. The SDK adds the property platform, set to android, to every decision.
To run only some of the surface's components, pass components = with their slugs. An empty list runs the surface workflow alone, and leaving it out runs every component. Each selection has its own cache entries.
Read surface properties
Your surface workflow can return open JSON under properties. The SDK exposes it as a JsonObject, and the shape is yours to define:
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
val banner = result.decision?.surfaceProperties?.get("banner") as? JsonObject
val text = (banner?.get("text") as? JsonPrimitive)?.takeIf { it.isString }?.contentProperties from a component workflow are in decision.componentBehaviors[slug]?.properties. For a meter, cast the typed property to Meterable to read its units:
import com.monetizationos.sdk.decision.Meterable
val meter = result.decision?.features?.get("article")?.properties?.get("views") as? Meterable
val remaining = meter?.remainingUnits // Double?Sign users in
Until a user signs in, the SDK identifies them by an anonymous identifier. The first decision asks MonetizationOS to mint one, and the SDK stores it in private SharedPreferences and sends it on every later call. Meters and grants for a signed-out user attach to it.
If several decisions start at once on a fresh install, each asks MonetizationOS for an identifier, and the SDK keeps only the first one that comes back. Meters counted against the others don't follow the user. If SharedPreferences doesn't keep the identifier, the SDK logs identity:store-failed and uses the identifier from memory until the process ends, so it doesn't ask for a new one on every decision.
To identify a signed-in user, give the SDK their JWT. Your JWT integration validates it on the server. For each call, the SDK picks the identity in this order: the token from identify, the token from jwtProvider, the stored anonymous identifier, and finally a new anonymous identifier from the server.
jwtProvider is the simplest option. The SDK calls it before every decision, redemption, and flush, so it should return the current token quickly and refresh it when needed:
import com.monetizationos.sdk.IdentityConfig
import kotlin.coroutines.cancellation.CancellationException
MOSConfig(
publicKey = "pk_live_...",
surface = "mobile-app",
app = AppInfo.from(context),
identity = IdentityConfig(
jwtProvider = {
try {
auth.freshAccessToken()
} catch (e: SignedOutException) {
null
} catch (e: CancellationException) {
throw e // Let a cancelled call stop.
} catch (e: Exception) {
auth.lastAccessToken
}
},
claimKey = "sub", // The JWT Claim Key of your JWT integration.
),
)auth stands for your own authentication layer. Set claimKey to the JWT Claim Key of the integration that validates these tokens. It defaults to "sub". The SDK keys a signed-in user's cached decisions and queued meter updates by that claim's value, a string or a number, so a refreshed token for the same user keeps them. A token without the claim is keyed by the whole token, so every refresh looks like a new user: the SDK clears the cached decisions and can drop queued meter updates.
If you would rather push tokens, call identify after sign-in and again with null after sign-out. It resolves the identity immediately without a network call, and returns an IdentifyResult with changed, previous, current, and linkPending:
mos.identify(token) // after sign-in, and at every launch while signed in
mos.identify(null) // after sign-outThe SDK doesn't persist the token you pass to identify. While a user stays signed in, call identify at every launch before any other SDK call. Otherwise the first call runs anonymously, which clears the user's cached decisions and can drop their queued meter updates. jwtProvider doesn't have this problem, because the SDK asks it for the token on every call.
When a token refresh fails for a transient reason, such as no connectivity, return the last token you have. Return null
only when the user is signed out. A null makes the SDK treat the user as signed out for that call, which switches to the
anonymous identity, clears their cached decisions, and can drop their queued meter updates at the next flush. If the provider
throws, the SDK catches the exception and treats it as null, so catch failures inside the provider.
What happens to the anonymous identifier
When the identity changes from the anonymous identifier to a JWT, the SDK clears the cached decisions, which belong to the old identity, and remembers the anonymous identifier as the previousAnonymousIdentifier. The next decision carries it as properties.previousAnonymousIdentifier. A surface workflow reads it as context.properties.previousAnonymousIdentifier and can link the two identities with utils.identity.link, so usage and grants from before sign-in follow the user. MonetizationOS doesn't link them on its own, so without that call nothing carries over. See Link Identities for the link call.
The SDK keeps the identifier, even across app launches, until a decision that carries it comes back authenticated. A token the server rejects, such as an expired one, gets an anonymous decision instead, so the SDK sends the identifier again with the next decision. result.linkedAnonymousIdentifier is true on the result that delivered it to your workflow. The identifier goes to the first account only. If the user signs straight into a different account before a decision delivers it, the SDK drops it.
After sign-out, the SDK goes back to the stored anonymous identifier and clears the cached decisions again. The next account to sign in gets that identifier as previousAnonymousIdentifier too, even if an earlier account already linked it. To forget the anonymous identifier, the cache, and the queue, so that the device starts as a new visitor, call reset(), for example after sign-out.
The SDK sends signed-in decisions with a fallback to anonymous, so a token the server rejects produces an anonymous decision, not an error. This applies to decisions only: redeem and flush fail with FailureReason.Unauthorized instead. Check result.decision?.identity?.isAuthenticated if the app needs to know which identity answered. The SDK doesn't cache an anonymous answer to a signed-in request or update meter counts from it, so the user's own cached decisions stay in place, and it logs cache:skipped.
Offline and metering
The SDK caches every successful decision per surface, identity, resource, and component selection. An entry lives for OfflineConfig.ttl, which defaults to 24 hours, or until the earliest offer token inside it expires, whichever comes first. That includes the offer tokens in a web paywall's HTML. The cache holds up to maxEntries entries, 50 by default. It never stores JWT claims, and its files live under noBackupFilesDir, so Auto Backup skips them.
import com.monetizationos.sdk.OfflineConfig
import kotlin.time.Duration.Companion.hours
offline = OfflineConfig(ttl = 24.hours, failOpen = true)The SDK keeps its data per environment, the environment your public key belongs to. Files go in noBackupFilesDir/mos-sdk/<environment>/ and the anonymous identifier in the SharedPreferences file com.monetizationos.sdk.<environment>, so a staging key and a production key in the same app never share an anonymous identifier, cache, queue, or meter counts.
When a request fails, decide serves the exact cached entry for the resource. Without one, and with fallbackToLatest on, which is the default, it serves the latest entry for the same surface, identity, and component selection. result.source says which happened:
result.source | Meaning |
|---|---|
DecisionSource.Network | A fresh decision from MonetizationOS. |
DecisionSource.Cache(ageMs) | The cached decision for this resource, ageMs milliseconds old. |
DecisionSource.Fallback(ageMs, fromResourceId) | The latest cached decision for the surface and identity, made for a different resource. |
DecisionSource.Unavailable | No decision. result.decision is null, and hasAccess returns failOpen. |
result.failure is set whenever the network was tried and failed, even if the cache served the result.
Fail-open. With no decision, hasAccess returns OfflineConfig.failOpen, which defaults to true. Set it to false to deny access when the app can't get a decision. The setting applies to the whole client, so check result.source where one screen needs a stricter rule. Set fallbackToLatest = false if answering from another resource's decision is wrong for your app.
To choose per call, pass policy = to decide: CachePolicy.NetworkFirst, which is the default, CachePolicy.CacheFirst(maxAge), CachePolicy.NetworkOnly, or CachePolicy.CacheOnly. After an event that changes what the user can access, call clearCache() to drop the cached decisions for every identity.
A cache entry matches on surface, identity, resource id, and component selection only. properties, meta, and other resource fields aren't part of the match, so CachePolicy.CacheFirst and the fallback to the exact entry can return a decision made with different values.
Metering offline
A decision served from the cache stands in for a request that would have consumed meters, so the SDK queues a counter update for each meter that decision consumed. flush() sends the queue, oldest first, and returns a FlushResult with sent, dropped, remaining, and failure. A successful network decision also flushes in the background when updates are queued, so an online session needs no explicit call.
Call flush() when the app comes to the foreground and when connectivity returns:
class MainActivity : ComponentActivity() {
override fun onStart() {
super.onStart()
lifecycleScope.launch { (application as ExampleApp).mos.flush() }
}
}The queue holds up to 500 updates, and it discards updates older than seven days and updates that belong to a user who has signed out. Concurrent calls to flush() share one flush. An update whose request timed out stays queued and is sent again, so if the first attempt reached MonetizationOS, a meter without Unique Resources counts that read twice.
Meter counts offline
Each network decision records the count of every meter in it. Until the next network decision, a meter in a decision served from the cache shows that count plus the reads the device has counted since, so remainingUnits keeps going down offline. A meter set to Unique Resources counts each resource once.
To turn access off when those reads use a meter up, set enforceMeters to true:
offline = OfflineConfig(enforceMeters = true)A locked meter has hasAccess set to false and lockedOffline set to true, and the SDK queues nothing for that read. A resource already counted in the current period stays open, even once the meter is used up. That's more lenient than online, where a used-up meter turns access off for every resource.
The cached decision is the one that granted access, so it has no paywall for the locked state. Show your own screen, or cache one from a surface of its own while the app is online and read it back with CachePolicy.CacheOnly. Like every cached decision, it expires after OfflineConfig.ttl.
import com.monetizationos.sdk.decision.Meterable
// Online, now and then: cache the offline-limit screen.
mos.decide(Resource(id = "offline-limit"), surface = "offline-limit")
// Offline, when a read comes back locked:
val meter = result.decision?.features?.get("article")?.properties?.get("enabled") as? Meterable
if (meter?.lockedOffline == true) {
val limit = mos.decide(Resource(id = "offline-limit"), policy = CachePolicy.CacheOnly, surface = "offline-limit")
// Show the experience in limit.decision.
}Until the next network decision, the device can't see a meter's period reset or reads on other devices, so offline the count can run out early or late.
Paywalls
A workflow resolves an experience and returns it under a property key of its choice. decision.experience(key, component) reads it from surfaceBehavior.properties[key], or from a component's properties when you pass component. It returns an Experience, or null when the key holds no experience, for example when the user already has access.
Experience.Nativecomes from an App experience that your workflow resolves withexperiences.resolveAsJson. Your app renders its JSON and its offers.Experience.Webcomes from an HTML experience that your workflow resolves withexperiences.resolveAsWebContent. The server renders the HTML, andMOSWebPaywallViewshows it.
Native paywall
A native experience holds your own JSON plus its offers. Decode the JSON into your own @Serializable type, and redeem an offer with redeem(offer.token) when the user taps it. redeem doesn't throw and returns a RedemptionResult:
import android.net.Uri
import com.monetizationos.sdk.Action
import com.monetizationos.sdk.MOS
import com.monetizationos.sdk.RedemptionResult
import com.monetizationos.sdk.decision.Experience
import com.monetizationos.sdk.decision.Offer
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonPrimitive
// The org's workflow picks a navigate action's URL: open only the web and your own app's scheme.
private val OPENABLE_SCHEMES = setOf("http", "https", "exampleapp")
@Serializable
private data class PaywallCopy(val headline: String, val body: String? = null)
@Composable
fun NativePaywall(mos: MOS, experience: Experience.Native) {
val scope = rememberCoroutineScope()
val copy = remember(experience) { runCatching { experience.decode(PaywallCopy.serializer()) }.getOrNull() }
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
Text(copy?.headline ?: "Subscribe")
experience.offers.mapNotNull { it.offer }.forEach { offer ->
val title = (offer.presentation["title"] as? JsonPrimitive)?.takeIf { it.isString }?.content ?: offer.id
Button(onClick = { scope.launch { redeem(mos, offer) } }) { Text(title) }
}
}
}
private suspend fun redeem(mos: MOS, offer: Offer) {
when (val outcome = mos.redeem(offer.token)) {
is RedemptionResult.Redeemed -> when (val action = outcome.action) {
is Action.Navigate -> if (Uri.parse(action.url).scheme?.lowercase() in OPENABLE_SCHEMES) openUrl(action.url)
is Action.Custom -> startPurchase(action.type, action.properties) // Your own code, e.g. custom:play-billing: buy with Play Billing.
is Action.NoAction -> refreshDecision() // Decide again so the screen reflects the new access.
else -> refreshDecision() // An action added in a later release.
}
is RedemptionResult.Declined -> showMessage(outcome.message) // The workflow refused the redemption.
is RedemptionResult.Failed -> showRetry() // It may not have run. For a timeout or server error it may have, so check before retrying.
}
}decode needs the Kotlin serialization compiler plugin, org.jetbrains.kotlin.plugin.serialization, in your app module, and it ignores keys your type doesn't declare. The inline form, experience.decode<PaywallCopy>(), needs Java 17 compileOptions and jvmTarget 17 in your module. The form above works at any target.
A redeemed offer clears the decision cache, as clearCache() does, so the next decision comes from MonetizationOS with the new access. An action of type custom, or of a custom: type such as custom:play-billing, arrives as Action.Custom with that type. A navigate action's URL comes from your organization's redemption workflow, so open it only if it's http, https, or your own app's scheme.
offer.presentation is whatever JSON your organization gave the offer. offer.storeProductId is its presentation.storeProductId, so you can look up the store's localized price with Play Billing. Identical redemptions in flight, such as a double tap, send once and share the result.
Web paywall
MOSWebPaywallView is an Android View, so a Compose screen hosts it in AndroidView. Keep a MOSWebPaywallRetainer in a ViewModel and pass it in, so that rotation, folding, and resizing move the live page into the new Activity instead of reloading it:
import com.monetizationos.sdk.android.MOSWebPaywallRetainer
import com.monetizationos.sdk.android.MOSWebPaywallView
class PaywallModel : ViewModel() {
val retainer = MOSWebPaywallRetainer()
override fun onCleared() = retainer.release()
}
@Composable
fun WebPaywall(mos: MOS, html: String, prices: PriceProvider, onClose: () -> Unit) {
val model: PaywallModel = viewModel()
// The view loads its HTML once, so a decision with new HTML needs a new view.
key(html) {
AndroidView(
factory = { context ->
MOSWebPaywallView(
context = context,
html = html,
mos = mos,
priceProvider = prices,
onRedemption = { redemption -> handle(redemption) }, // Act on it as for a native paywall.
onClose = onClose,
retainer = model.retainer,
)
},
onRelease = { it.destroy() },
modifier = Modifier.fillMaxWidth().height(380.dp),
)
}
}The page reaches the app only by navigating. A link to mos://redeem?token=... redeems the offer through mos, then calls onRedemption with the RedemptionResult. A link to mos://close calls onClose. An http or https link goes to onOpenUrl, which defaults to opening the system browser. The view blocks everything else. The callbacks run on the main thread. The view has no close control of its own, and if the WebView's renderer crashes, it logs webpaywall:process-terminated and calls onClose. Without a retainer, call destroy() when you remove the view.
In the experience's HTML template, link each plan to its offer token and mark where the store's price goes. storeProductId and fallbackPrice here are presentation fields on the offer, so use the names your offers define:
{{#mos-offer-slots-map.slot-0}}
<a href="mos://redeem?token={{mos-offer-token}}">
<span data-mos-product="{{storeProductId}}">{{fallbackPrice}}</span>
<span data-mos-product="{{storeProductId}}" data-mos-price="display-period"></span>
</a>
{{/mos-offer-slots-map.slot-0}}
<a href="mos://close">Not now</a>Any element with data-mos-product has its text replaced with the localized price that your PriceProvider returns for that product, and data-mos-price="display-period" uses the subscription period instead. Elements the provider can't price keep their fallback text. For a button that isn't a link, put data-mos-redeem="{{mos-offer-token}}" on the element.
The price provider answers from your own Play Billing code:
import com.monetizationos.sdk.PriceProvider
import com.monetizationos.sdk.StorePrice
class PlayPrices(private val billing: PlayBilling) : PriceProvider {
override suspend fun prices(productIds: Set<String>): Map<String, StorePrice> =
billing.formattedPrices(productIds).mapValues { (_, price) -> StorePrice(displayPrice = price) }
}Here PlayBilling stands for your own code that queries Play Billing and returns the formatted price for each product id. StorePrice also takes displayPeriod and introductoryDisplayPrice.
A Play subscription is priced per base plan, so set its offers' storeProductId to productId:basePlanId, such as premium:monthly (RevenueCat's format), and have the provider look up that base plan. A one-time product is its product ID alone.
Call your endpoints
callEndpoint sends a request to one of your environment's endpoints with the public key, so give the endpoint the Public Key access level. The SDK sends no user identity with these calls. If the endpoint's workflow needs to know the user, send their token yourself, for example in an Authorization header, and verify it in the workflow before you trust the request.
import com.monetizationos.sdk.EndpointMethod
import com.monetizationos.sdk.EndpointResult
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
when (val result = mos.callEndpoint("orders/checkout", body = buildJsonObject { put("item", itemId) })) {
is EndpointResult.Response -> if (result.response.isSuccess) {
val order = result.response.json // JsonElement?; also response.text and response.body
} else {
showError(result.response.status) // The endpoint answered with an error status.
}
is EndpointResult.Failed -> showRetry() // No response arrived. Check result.failure.reason.
}Every HTTP response comes back as EndpointResult.Response, whatever its status, with status, headers, body, json, text, and isSuccess. EndpointResult.Failed means no response arrived, with the reason RequestFailed, Timeout, or NotConfigured.
The method defaults to EndpointMethod.Post. Pass method = for Get, Put, Delete, or Patch, and query =, headers =, or timeout = as you need them. Without timeout, a call gets the full requestTimeout from MOSConfig, 5 seconds by default, even after other requests have timed out. Redemptions do too, so a slow workflow isn't cut short and reported as a timeout. A call with a body and Get or Delete fails without sending. The SDK drops headers it owns, such as X-MOS-Key, User-Agent, and Content-Type, from headers. To put values such as an id into the path, pass a list of segments instead of a path string, which encodes each segment whole, so "a/b" stays one segment. Endpoint calls are never retried, cached, or merged.
An installed app's endpoints live under the app's namespace. Get a handle with app(namespace) and call it the same way. The namespace is set when the app is installed, so read it from your configuration rather than hard-coding it:
val orders = mos.app(installedNamespace)
val recent = orders.call("orders/recent", method = EndpointMethod.Get, query = mapOf("page" to "1"))Privacy
The SDK reads no advertising ID, no Android ID, and no location. Requests go to the MonetizationOS API over HTTPS. Use these answers for the data safety form in the Play Console:
| Data type | Why it's collected |
|---|---|
| Device or other IDs | The anonymous identifier that the server mints and the SDK stores in private SharedPreferences. |
| User IDs | The subject of the JWT you pass, sent when you provide a token. |
| App interactions | The resource ids sent with decisions and deferred counter updates. |
- The purpose is app functionality only. The data isn't used for tracking.
- The data is encrypted in transit.
These answers cover only what the SDK collects. Your own data safety answers still need to cover everything else your app collects.
Example app
The Showcase app in the SDK repository has one Jetpack Compose screen per use case, such as gating content, metered access, paywalls, offer redemption, sign-in, and offline behavior. It runs on bundled fixtures with no account or key, and a Live mode points it at your own environment. See Examples/Showcase for the source and run steps.
Related
Surfaces & Components
How a surface and its workflows shape the decision your app receives.
Features
How meterable and boolean feature properties model access and usage.
Offers
How offers and their tokens work, and how redemption runs.
Authentication & Identity
Configure the JWT integration that validates the tokens your app sends.
Link Identities
Carry anonymous grants and usage over when a user signs up or logs in.
Make a Surface Decision in an Android app
Call the Surface Decision API directly, without the SDK.