Skip to content
Optima docs
SDKsAndroid SDK

Consent

Android SDK v1.4.0 — Consent

The store

Consent lives in one ConsentState, persisted to SharedPreferences under the key _optima_consent and mirrored in memory as a StateFlow (optima.consent.changes). It survives process death and app restarts; it does not survive reset() (see chapter 3), because a reset means a different person is now using the device, and their consent is not the previous person's to inherit.

data class ConsentState(
    val v: Int = 1,
    val decisions: Map<String, Boolean> = emptyMap(),
    val decidedAt: Long? = null,
    val bannerId: String? = null,
    val policy: Map<String, Any?>? = null,
    val lang: String? = null,
)

decided (decidedAt != null) is the load-bearing question: it's what beforeDecision = BUFFER gates on, and what consent.can(...) and the purposes declaration below both key off of. granted is the sorted list of purposes currently true.

beforeDecision semantics

  • BUFFER (the default): every hit built before a decision exists still queues into the outbox, but the tracker's flush loop refuses to send while !consent.get().decided — hits pile up locally instead of leaving the device. The moment the first consent.set(...) call completes its local write, the queue is unblocked (tracker.scheduleFlush()) and everything queued so far ships in the next batch(es), each carrying the now-decided consent declaration. Each hit otherwise carries the consent declaration as it stood when it was collected, so a hit collected before a grant is never sent under that grant; a batch is split at every consent change.
  • SEND: hits flush on the normal batch/coalesce schedule regardless of whether a decision exists yet. A hit collected before any decision leaves with no consent block at all (Edge treats it as undeclared under the SDK key's consent mode), not with an empty purposes: [] list; BUFFER, the default, instead holds such hits until the first decision. This is correct when your own consent UI gates calling the SDK at all (you don't Optima.init until consent is known), or under source = CMP (forced automatically — see chapter 2), where the CMP owns the decision and there's nothing of ours to buffer for.

Buffered hits are not exempt from the 200-entry outbox cap — a very long undecided period on a very active app can still lose the oldest hits, same as any other backlog.

Delivery of decisions

consent.set(...) posts the decision on the same 5-attempt retry ladder as identify (Retry-After honoured; a final give-up emits Error("consent", cause)). The decision is also recorded durably before the first attempt (_optima_consent_pending, per device id). If every attempt fails, or the process dies mid-ladder, it is replayed on the next launch, foreground or successful track flush until Edge acknowledges it (or rejects it with a 4xx). reset() does not discard a pending decision from the previous device id.

The omit-vs-[] declaration rule

This is the single most important consent detail in the whole SDK, and it's identical to the Web SDK's rule and the ADR behind it in optima's DECISIONS.md. ConsentStore.declaration():

if (source == ConsentSource.OPTIMA && s.decided) out.put("purposes", JSONArray(s.granted))
  • No decision yet (!decided): the purposes key is omitted entirely from the request's consent block (in fact, if nothing else — no TCF string, no GCM map, no keys — is set either, the whole consent key is omitted from the request body). Omission means "consent is unknown," and the server treats an unknown purpose per its own configured default (which, depending on the purpose's collection-gate configuration, ranges from "allow" to "quarantine until known" — that policy lives entirely server-side and the SDK has no opinion on it).
  • A decision exists, everything rejected: purposes is sent as an explicit empty array []. This is not the same thing as omission — [] means "we asked, and the answer was no to everything," a materially different fact than "we haven't asked." Never conflate these two states in your own code if you ever touch ConsentState directly; the built-in banner and consent.set(...) already get this right, this note exists so a custom consent UI built against consent.set doesn't accidentally collapse them.

source = CMP never declares purposes at all, decided or not — see below.

The built-in banner

When consent.source = ConsentSource.OPTIMA (the default) and the content engine's content fetch for the implicit overlay slot (or any declared slot) returns a banner_consent-type item, the Compose module's OptimaHost renders it automatically via ConsentBannerRenderer — you don't need to write any banner UI yourself. It's a two-stage surface:

  1. Summary: title + body copy, and three actions — Accept all, Reject all, Manage.
  2. Manage (reached via the third button): a per-purpose Switch row for every purpose in the item's purpose_details payload, seeded from the current decision (or false if undecided), plus a Save button.

Copy is resolved per language from the item's payload.languages map, with a fallback ladder: your configured banner language (if you pass one) → the device's full locale tag → the device's primary language subtag → "en" → whatever language key happens to exist first. Each of Accept all, Reject all, and Save calls consent.set(decisions, ConsentMeta(bannerId = item.id, lang = resolvedLang, policy = item's policy block)) and then the renderer itself calls content.refresh() right after — so the very next content poll stops returning the banner (there's no separate "dismiss" call for a consent decision; posting the decision is what makes the banner go away, and the renderer never calls onDismiss on this item type for that reason).

If you're writing your own consent UI instead of using the built-in one (perhaps because your design system doesn't fit a Material dialog), the recipe is: fetch the banner_consent item yourself (headless — chapter 5), render your own screen from its payload.languages/payload.purpose_details, and call consent.set(...) with the same shape. The ConsentMeta.policy field exists precisely so a custom UI can still round-trip the policy-version metadata the server expects, without needing to understand its internal shape.

CMP passthrough

Two independent knobs, both covered from the config side in chapter 2:

  • TCF: read automatically, always, regardless of source — TcfSource reads IABTCF_TCString from the app's default SharedPreferences (the location every IAB-compliant CMP SDK writes it to) and observes it for changes, feeding consent.setTCF(...) internally. You never need to call consent.setTCF yourself unless you're deliberately overriding what a CMP wrote, or testing without a real CMP installed.
  • GCM / arbitrary keys: manual only — there is no Google Consent Mode dataLayer equivalent to read on Android (that's a web-page concept). Call consent.setGCM(mapOf("ad_storage" to GcmValue.DENIED, ...)) / consent.setKeys(mapOf(...)) yourself, typically from your CMP SDK's own consent-changed callback.

source = CMP additionally stops the SDK from declaring its own purposes array at all (see the omit-vs-[] section above — under CMP that whole branch of declaration() is skipped regardless of ConsentState.decided), and diverts any served banner_consent item away from the built-in renderer into a plain ContentItem event for you to route into your CMP's own UI flow instead — see chapter 3.

Gating third-party SDKs

consent.can(trackerName) plus consent.changes is the pattern for deciding, at runtime, whether a third-party SDK you initialize yourself is allowed to run — the SDK doesn't (and can't) reach into another vendor's SDK and stop it, but it can tell you the answer so your own init code can decide. A typical Firebase Analytics gate, initialized lazily and re-checked on every consent change:

class AnalyticsGate(private val app: Application) {
    private var initialized = false

    fun start(scope: CoroutineScope) {
        scope.launch {
            Optima.instance.consent.changes.collect { _ ->
                val allowed = Optima.instance.consent.can("firebase_analytics")
                if (allowed && !initialized) {
                    FirebaseAnalytics.getInstance(app).setAnalyticsCollectionEnabled(true)
                    initialized = true
                } else if (!allowed && initialized) {
                    FirebaseAnalytics.getInstance(app).setAnalyticsCollectionEnabled(false)
                    // Firebase keeps running once initialized; disabling collection is the
                    // available lever — a true "unload" isn't offered by that SDK either.
                }
            }
        }
    }
}

"firebase_analytics" here must be a name registered in the Optima console's tracker inventory (edge_trackers, the same table the SDK reads via GET /edge/v1/trackers), with its purpose pointed at whichever consent purpose should gate it. consent.can returns false (fail-closed) for any name that isn't in that inventory or hasn't loaded yet — a typo in the name you pass silently gates the SDK off forever, so double-check it against the console.

Revocation

ConsentRevoked(purposes) fires whenever a consent.set(...) call flips a previously-true purpose to false. A running third-party SDK cannot be unloaded — there is no Android API to un-initialize an already-initialized library's native code, background threads, or file handles it opened. The event is your signal to do whatever your SDK's own "stop/disable" API offers (as in the Firebase example above), and the app is the one that decides what "stop" means for each vendor it embeds — the platform SDK itself has no opinion on what compliance requires you to do in response.

reset() on logout

reset() clears _optima_consent back to a fresh ConsentState() (undecided, no purposes) as one of its first steps, and emits ConsentChange with that fresh state. On a shared/kiosk device, call it on every logout — the next person who picks up the device should see the consent banner again, not inherit the previous person's decision. See chapter 3 for the full ordering of what else reset() clears.

On this page