Android (Kotlin)
Install and wire the Rovenue SDK in an Android/Kotlin app.
Add the repository
Versions 0.29.0 and later are published to Broverse's own Maven repository (maven.broverse.ai); 0.28.6 and earlier are on Maven Central only, so keep mavenCentral(). Add the repository to settings.gradle.kts, before mavenCentral():
// settings.gradle.kts
dependencyResolutionManagement {
repositories {
maven("https://maven.broverse.ai") { content { includeGroup("io.rovenue") } }
google()
mavenCentral()
}
}Or in Groovy DSL (settings.gradle):
// settings.gradle
dependencyResolutionManagement {
repositories {
maven { url 'https://maven.broverse.ai'; content { includeGroup 'io.rovenue' } }
google()
mavenCentral()
}
}If your app declares repositories in the root build.gradle under allprojects { repositories { ... } } instead of in settings, add the same maven line there.
Add the dependency
Add the SDK to your module-level build.gradle.kts:
dependencies {
implementation("io.rovenue:sdk:0.33.0")
}Or in Groovy DSL (build.gradle):
dependencies {
implementation 'io.rovenue:sdk:0.33.0'
}The SDK drives Play Billing natively. Receipt processing and server-side validation happen automatically via the Rovenue API — you do not need to call Play Billing directly.
R8 / minification. Release builds with isMinifyEnabled = true need no keep rules of your own. The SDK's native core is reached through JNA, which binds classes, fields and callbacks by name at runtime; the AAR ships consumer R8 rules that keep them (JNA itself and the generated bindings), and Gradle applies them to your app automatically. The rest of the SDK may be shrunk and renamed as usual.
16 KB page sizes. The native libraries the SDK brings are aligned for devices with 16 KB memory pages, as Google Play requires of apps targeting Android 15 and higher: its own core, and JNA's dispatcher (the SDK depends on JNA 5.18.1).
Configure the SDK
Call Rovenue.configure once in your Application.onCreate(), before any component starts:
import android.app.Application
import dev.rovenue.sdk.Rovenue
import dev.rovenue.sdk.generated.LogLevel
class App : Application() {
override fun onCreate() {
super.onCreate()
val versionName = packageManager
.getPackageInfo(packageName, 0)
.versionName
Rovenue.configure(
apiKey = "rov_pk_test_FjVJczKFPhknOcx141VbIl0EiRsQ",
logLevel = LogLevel.INFO,
appVersion = versionName,
context = this,
)
}
}Pass context (the Application itself works, or any Context — the SDK
keeps context.applicationContext). Without it, getOfferings() still
works, but purchase() and restorePurchases() throw
RovenueException(kind = ErrorKind.STORE_PROBLEM) — Play Billing needs a
Context to bind to, and there is no fallback.
Self-hosting? baseUrl is optional and defaults to the hosted endpoint https://api.rovenue.io. Override it to point at your own deployment, e.g. Rovenue.configure(apiKey = "rov_pk_test_FjVJczKFPhknOcx141VbIl0EiRsQ", baseUrl = "https://api.acme.com", appVersion = versionName). The host must use https:// — plain http:// is accepted only for localhost during local development.
Register App in your AndroidManifest.xml:
<application android:name=".App" ...>Types on this page
// Kotlin mirror of Rovenue.configure's parameters — there is no separate
// RovenueConfig type on this platform, only named parameters.
fun configure(
apiKey: String,
baseUrl: String? = null, // optional — defaults to https://api.rovenue.io
logLevel: LogLevel = LogLevel.WARN, // OFF | ERROR | WARN | INFO | DEBUG | TRACE
appVersion: String? = null,
context: Context? = null, // required for purchase()/restorePurchases()
environment: String? = null,
)| Field | Type | Description |
|---|---|---|
apiKey | String | Public SDK key from your Rovenue dashboard. Prefix rov_pk_live_ (Production) or rov_pk_test_ (Sandbox). |
baseUrl | String? | Optional. Defaults to https://api.rovenue.io. Override only when self-hosting (https://; http:// allowed for localhost only). |
logLevel | LogLevel | Verbosity of SDK logs. Defaults to WARN — turn up to INFO/DEBUG locally, never ship DEBUG/TRACE in production. |
appVersion | String? | Overrides the version read from the package manager. |
context | Context? | An Android Context (the SDK stores context.applicationContext). Pass it — purchase() and restorePurchases() throw STORE_PROBLEM without it. |
environment | String? | Optional environment label forwarded with requests. |
Call configure in Application.onCreate — not inside an Activity. Calling
any other SDK method before configure has run throws a plain
IllegalStateException — not a RovenueException — so catch (e: RovenueException) will not observe it. This is a programming error to fix by
ordering (always configure first), not a condition to catch. See Calling
the SDK before configure().
App lifecycle
The SDK observes the app lifecycle itself (configure registers a ProcessLifecycleOwner observer) — there is no foreground/background wiring to add. Rovenue.shared.setForeground(...) remains as a manual override; you do not need to call it.
Purchases
Use getOfferings() to fetch products configured in your Rovenue dashboard, then purchase(pkg) to drive the full Play Billing flow. The SDK validates the receipt server-side and resolves with updated entitlements.
import dev.rovenue.sdk.Rovenue
import dev.rovenue.sdk.RovenueException
import dev.rovenue.sdk.generated.ErrorKind
val offerings = Rovenue.shared.getOfferings()
val pkg = offerings.current?.packages?.firstOrNull()
if (pkg != null) {
try {
// `activity` is your current Activity — Play Billing requires it.
val result = Rovenue.shared.purchase(activity, pkg)
if (result.isDeferred) {
// Ask-to-Buy / parental-control hold — no entitlements yet. The SDK
// reconciles it in the background; collect Rovenue.shared.changes for
// ChangeEvent.ENTITLEMENTS_CHANGED to know when it resolves.
} else {
// result.entitlements and result.virtualCurrencies are already up to date
}
} catch (e: RovenueException) {
when (e.kind) {
ErrorKind.PURCHASE_CANCELED -> Unit // User dismissed the store sheet — no action needed
else -> throw e
}
}
}
// Re-validate all prior transactions (e.g. after reinstall):
Rovenue.shared.restorePurchases(activity)restorePurchases asks Google Play for the purchases the account owns
(subscriptions and one-time products), posts each for the current user and
refreshes. It throws a RovenueException when the Play query or a receipt
POST failed and no entitlement is active afterwards: isRetryable is true
when trying again can help (offline, timeout, rate limit, 5xx, Play
unavailable), otherwise it carries the server's refusal, for example
ErrorKind.CONFLICT with serverCode "RECEIPT_IN_USE" when another account
holds the purchase. It no longer returns an empty success in that case.
A second purchase() while a Play purchase sheet is up throws
ErrorKind.STORE_PROBLEM ("another purchase is already in progress") before
Play is asked. Disable the buy button while a purchase is pending and do not
present this as a failed payment. If Play never answers a sheet, a purchase()
made 2 minutes or more after it opened takes its place, and the earlier call
throws ErrorKind.STORE_PROBLEM ("the purchase sheet never answered and a newer
purchase replaced it"). See When a restore fails for what to show in each case.
// Kotlin mirror of PurchaseResult
data class PurchaseResult(
val entitlements: List<Entitlement>,
val virtualCurrencies: Map<String, Long>,
val productId: String,
val storeTransactionId: String,
val isDeferred: Boolean, // true for an Ask-to-Buy / parental-control hold
)
data class Entitlement(
val id: String,
val isActive: Boolean,
val productIdentifier: String,
val store: String,
val expiresIso: String?, // ISO 8601 — present for time-limited entitlements
)| Field | Type | Description |
|---|---|---|
entitlements | List<Entitlement> | Updated entitlement list after the purchase. |
virtualCurrencies | Map<String, Long> | Updated virtual-currency balances after the purchase (currency code → amount). |
productId | String | The product identifier that was purchased. |
storeTransactionId | String | The Play Store transaction ID. |
isDeferred | Boolean | true when the purchase is pending external approval — no entitlements are granted yet. |
Free trials and intro offers
purchase(activity, pkg) redeems pkg.product.defaultOption: of the offers Google Play returns for this
user (only the ones they are eligible for) on the product's base plan, the longest free trial, else the
cheapest introductory price, else the base plan. product.introPrice and
product.isEligibleForIntroOffer describe that option. The dashboard's Base plan ID / Offer ID
override the choice; tag an offer rovenue-ignore-offer in the Play Console to keep it out (do this for
"developer determined" offers, which Play returns to everyone). To buy a specific offer, pass one of
product.subscriptionOptions: purchase(activity, pkg, option). See
Default offer (Android).
Win-back offers
Tag a "developer determined" Play offer rovenue-winback to make it a win-back offer: it is never the
default, product.discounts lists it as WIN_BACK, and purchase(activity, product, winBackOffer) buys
it. Play returns such an offer to every user and keeps no purchase history, so eligibleWinBackOffers
lists it only for a user the Rovenue server saw hold that Play subscription and no longer hold it
(lapsedSubscriptions on /v1/me/entitlements, cached with the entitlements). A user who never
subscribed gets none, and so does one whose history is unknown: before the first entitlements refresh,
or offline past the seven-day grace. A funnel's product.has_winback follows the same rule. See
Win-back offers.
Who acknowledges a Play purchase
The SDK acknowledges (subscriptions, non-consumables) or consumes (consumables) every Google Play purchase. It does so on the device, only after the server has verified the receipt, and it re-checks the token's state with Play first, so a purchase that is already acknowledged is left alone. Once the server has verified the purchase, purchase() returns its PurchaseResult and never throws: if Play cannot take the acknowledgement right then (the device went offline, Play Billing is unavailable), the SDK retries a few times and then leaves it to the next reconcile, which runs on every app launch and foreground — well inside Play's three-day window before it auto-refunds an unacknowledged purchase. A verification failure is never acknowledged, so Play refunds that purchase as intended.
The Rovenue server is a second, delayed acknowledger: a few minutes after it verified and recorded a purchase it acknowledges it if Play still says unacknowledged (it never consumes). In the normal flow the SDK has already finished and the server does nothing. When the server got there first, the SDK's own acknowledge or consume may answer ITEM_NOT_OWNED; the SDK treats that as done, never as an error. See Server-side acknowledgement for the service-account permission it needs.
There is no PurchaseCancelledException/PurchasePendingException — every SDK method throws the single RovenueException, discriminated by .kind. And there is no PURCHASE_PENDING kind at all: as of 0.16.0, a deferred purchase does not throw; it returns normally with isDeferred = true. See Reference: Errors for the full 24-value ErrorKind taxonomy and Processing Purchases for the complete purchase API and the StoreProduct shape.
Funnels
RovenueFunnelView.setPlacement(placementId, locale, handlers) resolves a
placement into the funnel the current subscriber should see (see Placements &
Funnels) and draws it. A placement that serves
nothing is not an error: the view draws nothing and reports onUnavailable.
In a debug build on a Sandbox key it shows the funnel's latest draft and keeps
it live. Call view.close() when you take the view away for good (see Show a
Funnel):
import android.content.Context
import dev.rovenue.sdk.funnelui.FunnelHostHandlers
import dev.rovenue.sdk.funnelui.RovenueFunnelView
import dev.rovenue.sdk.funnelui.wireName
fun showOnboarding(context: Context): RovenueFunnelView {
val view = RovenueFunnelView(context)
view.setPlacement(
placementId = "onboarding",
locale = "en",
handlers = FunnelHostHandlers(
onUnavailable = { unavailable -> println(unavailable.reason.wireName) },
onCompleted = { println("completed") },
onDismissed = { println("dismissed") },
),
)
return view
}Purchase attribution is automatic: the funnel's presentedContext is
attached to the next purchase for you.
See Placements for how placements resolve to a funnel or an A/B experiment variant.
Observing changes
Rovenue.shared.changes is a SharedFlow of change events. Collect it from a coroutine scope tied to your component's lifecycle:
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.lifecycle.Lifecycle
import dev.rovenue.sdk.Rovenue
// Inside an Activity or Fragment:
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
Rovenue.shared.changes.collect { event ->
// event: ChangeEvent (ENTITLEMENTS_CHANGED | IDENTITY_CHANGED | VIRTUAL_CURRENCIES_CHANGED)
println("Rovenue change: $event")
}
}
}Collect Rovenue.shared.changes from an Activity or ViewModel scope — not from inside the SDK's own internal scope. Calling Rovenue.shared.shutdown() from inside an active collector's coroutine may interrupt the collector mid-flight.
Suspend functions
SDK methods such as identify, logOut, refreshEntitlements, and refreshVirtualCurrencies are suspend functions. Call them from a coroutine:
lifecycleScope.launch {
// After your auth flow completes. Your backend mints identityToken for this
// user with the secret key (POST /v1/identity-tokens):
Rovenue.shared.identify("user_123", identityToken)
// When your user signs out:
Rovenue.shared.logOut()
val entitlements = Rovenue.shared.refreshEntitlements()
}See Identifying Users for the full identity model, including what happens when identify and logOut are called.
Funnels
To drive a session yourself, Rovenue.shared.getFunnel(placementId, locale)
returns a FunnelResolution: FunnelResolution.Funnel with the session
already open, or FunnelResolution.Unavailable with the reason
(packages/sdk-kotlin/src/main/kotlin/dev/rovenue/sdk/Rovenue.kt). Wrap the
session in a FunnelDriver and attach it with bind(driver) — a fixed
snapshot, with no live draft refresh. Full path: Show a
funnel.
import dev.rovenue.sdk.funnelui.FunnelDriver
import dev.rovenue.sdk.funnelui.FunnelResolution
import dev.rovenue.sdk.funnelui.UniffiFunnelSession
import dev.rovenue.sdk.funnelui.wireName
when (val resolution = Rovenue.shared.getFunnel(placementId = "onboarding")) {
is FunnelResolution.Funnel -> {
val driver = FunnelDriver(UniffiFunnelSession(resolution.funnel.session))
println(driver.stateJson())
}
is FunnelResolution.Unavailable -> println(resolution.unavailable.reason.wireName)
}What's next
- Identifying Users — link your backend user to the Rovenue subscriber.
- Entitlements — read and gate on active subscriptions.
- Virtual Currencies — read virtual-currency balances and grant/spend via server-side APIs.
- Processing Purchases — full purchase API and error handling.
- App Lifecycle — foreground/background wiring in depth.
- Reference: Methods — full method reference.
- Reference: Types — all SDK types in one place.
- SDK API Reference — the generated Dokka reference for every public Kotlin type and method, at
/api/sdk-kotlin/.