Display a paywall

Present the paywall or onboarding flow assigned to a location, pass it data and handle how it ended.

presentFlow shows the paywall or onboarding flow assigned to a paywall location and returns how it ended. You design, deploy and assign flows in Studio; see Paywalls in your app and Paywall locations.

Add the paywall renderer

Flows are drawn with Android's own views by the com.voidhash:voidhash-ui artifact. Depend on it next to the SDK, with the same version:

app/build.gradle.kts
dependencies {
    implementation("com.voidhash:voidhash:0.3.0")
    implementation("com.voidhash:voidhash-ui:0.3.0")
}

Its native library ships for arm64-v8a, armeabi-v7a and x86_64; on other devices no flow can be drawn.

The SDK finds the module's renderer on its own; configure it with the capabilities your flows may use:

App.kt
import com.voidhash.sdk.FlowCapability
import com.voidhash.sdk.Voidhash
import com.voidhash.sdk.VoidhashOptions

val voidhash = Voidhash.configure(
    context = this,
    publishableKey = "vh_pk_...",
    options = VoidhashOptions(
        flowCapabilities = setOf(FlowCapability.LINKS, FlowCapability.ATTRIBUTES),
    ),
)

Without the module, presentFlow throws a FlowException with the reason RENDERER_MISSING.

Present a flow

A location is the spot in your app where a flow is shown, such as onboarding. Pass an activity and the location's slug:

import com.voidhash.sdk.FlowException
import com.voidhash.sdk.FlowResult

lifecycleScope.launch {
    val result = try {
        voidhash.presentFlow(activity, "onboarding")
    } catch (error: FlowException) {
        showOwnUpgradeScreen()
        return@launch
    }
    when (result.outcome) {
        FlowResult.PURCHASED, FlowResult.RESTORED -> refreshAccess()
        FlowResult.DISMISSED -> Unit
        "completed" -> saveAnswers(result.outcome, result.output)
    }
}

The flow covers the activity in a fullscreen dialog. presentFlow suspends until the flow is gone and returns a FlowResult, which has the same shape for every ending:

PropertyValue
outcomeHow the flow ended, as a string. See the table below.
outputThe flow's outputs by name. Empty when the flow has none.
productIdThe slug of the product bought when the outcome is purchased; otherwise null.
OutcomeWhen
purchased (FlowResult.PURCHASED)A purchase in a paywall succeeded.
restored (FlowResult.RESTORED)A restore in a paywall succeeded.
dismissed (FlowResult.DISMISSED)The flow's close action, the back button on the first screen, dismissFlow(), or another flow presented in its place.
Any other, such as completedThe flow ran a Finish flow action. The outcome is the one the action names, or completed when it names none.

A flow that can't be shown is a failure, not an outcome: presentFlow throws a FlowException. See Handle failures.

Pass inputs

Inputs are named values your app passes to the flow at a location, such as the person's first name or a number of credits. Each one is a String, a number, a Boolean or a List<String> (each string once, at most 100 of at most 200 characters). Pass them by name:

val result = voidhash.presentFlow(
    activity,
    "onboarding",
    input = mapOf("firstName" to "Ada", "credits" to 3),
)

An input you don't pass keeps the default it has in the flow, and a value of any other type is dropped with a warning.

To change inputs while the flow is on screen, call updateFlowInput with the ones that changed:

voidhash.updateFlowInput(mapOf("credits" to 2))

It does nothing when no flow is shown.

Read outputs

Outputs are named values the flow hands back, such as an answer the person picked. result.output holds them however the flow ended, also after a purchase or when the person closed it. Each value is a String, a Double or a Boolean:

val result = voidhash.presentFlow(activity, "onboarding")
val goal = result.output["goal"] as? String ?: "none"
val reminders = result.output["reminders"] as? Boolean ?: false

Read an output with a default: a flow that doesn't have it leaves it out.

Handle app actions

A flow can call a function of your app while it is shown, for example to open your own picker. Pass a handler for each action by name. A handler receives the action's arguments by name and returns the fields of its reply:

import com.voidhash.sdk.FlowActionHandler

val pickGoal = FlowActionHandler { arguments ->
    // Show your own picker here, starting from the goal the flow passed.
    val current = arguments["current"] as? String ?: "sleep"
    mapOf("goal" to current)
}

val result = voidhash.presentFlow(activity, "onboarding", actions = mapOf("pickGoal" to pickGoal))

Arguments and replies hold String, number and Boolean values; numbers arrive as Double. Handlers are suspending functions, and one that is still running when the flow ends is cancelled.

The person is never left waiting on your app. When a handler throws, or the flow calls an action you passed no handler for, the call fails inside the flow and the flow carries on as its designer set it up for a failed call. In a debug build the SDK logs each call to an action without a handler, with the action's name and the location.

Interface revisions and typed code

What a location exchanges with your app (its inputs, outputs, outcomes and app actions) is its interface, and every change to it makes a new revision. Tell the SDK which revision your app was built against, so a person is only shown a flow this version of your app can answer:

VoidhashOptions(
    flowRevisions = mapOf("onboarding" to 3),
)

flowRevisions applies to every presentFlow for that location and to preloading. To set it for a single call, pass revision: presentFlow(activity, "onboarding", revision = 3). A location without a revision counts as revision 0: it is shown flows that call no app action and finish only as completed.

The Voidhash CLI can generate typed code for each location, which carries the revision for you. With it you present a FlowLocation instead of a slug, pass the inputs and actions as types, and get a TypedFlowResult whose outcome and output are typed too:

val result = voidhash.presentFlow(
    activity,
    OnboardingFlow.location,
    OnboardingFlow.Input(firstName = "Ada", credits = 3.0),
    actions,
)
if (result.outcome == OnboardingFlow.Outcome.Completed) saveGoal(result.output.goal)

For a location without inputs or actions, pass NoFlowInput and NoFlowActions.

While a flow is on screen

A paywall ends when a purchase or restore succeeds. An onboarding flow keeps running after one, so it ends with the outcome it finishes with or dismissed, and never with purchased or restored. Check access with hasActivePerk after it ends.

A failed or cancelled purchase shows its error inside the flow and leaves it open. In observer mode, purchases in flows fail with READ_ONLY_PURCHASE_NOT_ALLOWED.

When a paywall has an On close screen, such as a last offer, the first close attempt shows it instead of closing, and presentFlow keeps waiting. It shows at most once per presentation.

Only one flow is on screen at a time. dismissFlow() closes it at once, and so does cancelling the coroutine that called presentFlow. dismissFlow() also cancels a flow that is still loading, so it never appears later. Call it from any thread.

A flow stays up when Android recreates the activity for a configuration change, such as a rotation, a switch to dark mode or another font size, and presentFlow keeps waiting. Call presentFlow from a coroutine that outlives the activity, such as one in viewModelScope: one launched in the activity's lifecycleScope is cancelled when the activity is destroyed, which dismisses the flow. An activity that is destroyed for good, or isn't recreated within 5 seconds, closes the flow with the outcome dismissed.

A flow that comes back on screen, after a recreation or after the app was in the background, comes back where the person was: on the same screen, with the screens before it for the back button, the keyboard on the field that had it, its saved progress and the inputs as you last set them. What it was waiting for goes on: a timer, your app's answer to an app action, a purchase in progress. Scroll positions start at the top again, and a text field bound to no variable comes back empty. It still counts as one view, and tracks no screen or event of its own again. A later presentation of the flow starts at its first screen. What the SDK keeps to bring the flow back, which can include what was typed (never into a password field), stays in memory with the presentation: it is never written to disk or logged.

Flows follow the font size people choose, and lay their text out again when it changes. An activity that declares fontScale in its android:configChanges isn't recreated for a font size change, so the flow keeps its screen, scroll positions and the keyboard and only lays its text out again.

Handle failures

presentFlow throws a FlowException when the flow can't be shown, or stops because it can no longer be drawn. Its reason is a FlowFailure, and its code is FLOW_ plus the reason, such as FLOW_NOT_ASSIGNED.

import com.voidhash.sdk.FlowException
import com.voidhash.sdk.FlowFailure

try {
    voidhash.presentFlow(activity, "onboarding")
} catch (error: FlowException) {
    if (error.reason != FlowFailure.NOT_ASSIGNED) Log.w("App", "Flow failed: ${error.code}")
    showOwnUpgradeScreen()
}
ReasonMeaning
NOT_ASSIGNEDNothing is assigned to the location for this person, the location doesn't exist or is archived, or none of its recent builds is one this app can show.
UNAVAILABLEThe device never resolved this location and Voidhash is unreachable, the flow couldn't be downloaded or verified, or it wasn't ready to show within 15 seconds.
RENDERER_MISSINGThe app doesn't depend on com.voidhash:voidhash-ui.
UNSUPPORTED_PACKAGEThe renderer can't draw this build: its native library doesn't ship for this device's CPU, or the build uses a package format this app's SDK build can't read. abiVersion names the build's format.
PRESENTATION_FAILEDThe flow couldn't be shown, or three frames in a row failed to draw while it was on screen. A single failed frame is drawn again.
DISABLEDThe client is disabled or shut down.

Keep a fallback screen for important entry points so people can always upgrade.

Grant capabilities

Showing screens, purchases, restores, closing and Track event need no permission. Other actions need a capability in flowCapabilities; without it, the action is skipped and the SDK logs a warning. Only LINKS is granted by default.

CapabilityLets a flow
LINKSRun Open URL.
ATTRIBUTESRun Set user attribute on the current person.
NOTIFICATIONSRun Request permission for notifications.
TRACKINGRun Request permission for tracking. Android has no such prompt: it is unavailable.

A Request permission step for a permission you didn't grant, or for tracking, goes on at its Unavailable exit.

On Android 13 and later, a notification request shows the system prompt. The SDK doesn't add the permission to your manifest: declare it, or the flow hears that notifications are unavailable:

AndroidManifest.xml
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />

On earlier versions there is no prompt: the flow learns whether notifications are enabled for your app.

To ask in your own way, register a handler for that permission, by its name; the SDK uses it instead of its prompt:

import android.Manifest
import android.app.Activity
import androidx.activity.ComponentActivity
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.app.NotificationManagerCompat
import com.voidhash.sdk.FlowCapability
import com.voidhash.sdk.FlowPermissionHandler
import com.voidhash.sdk.FlowPermissionResult
import com.voidhash.sdk.FlowPermissionStatus
import com.voidhash.sdk.VoidhashOptions
import kotlin.coroutines.resume
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext

class NotificationHandler : FlowPermissionHandler {
    override suspend fun status(activity: Activity) =
        if (NotificationManagerCompat.from(activity).areNotificationsEnabled()) {
            FlowPermissionStatus.GRANTED
        } else {
            FlowPermissionStatus.NOT_DETERMINED
        }

    override suspend fun request(activity: Activity): FlowPermissionResult {
        val registry = (activity as? ComponentActivity)?.activityResultRegistry
            ?: return FlowPermissionResult.UNAVAILABLE
        return withContext(Dispatchers.Main) {
            suspendCancellableCoroutine { continuation ->
                lateinit var launcher: ActivityResultLauncher<String>
                launcher = registry.register("app.notifications", ActivityResultContracts.RequestPermission()) { granted ->
                    launcher.unregister()
                    continuation.resume(if (granted) FlowPermissionResult.GRANTED else FlowPermissionResult.DENIED)
                }
                continuation.invokeOnCancellation { launcher.unregister() }
                launcher.launch(Manifest.permission.POST_NOTIFICATIONS)
            }
        }
    }
}

val options = VoidhashOptions(
    flowCapabilities = setOf(FlowCapability.LINKS, FlowCapability.NOTIFICATIONS),
    flowPermissionHandlers = mapOf(FlowCapability.NOTIFICATIONS.wireName to NotificationHandler()),
)

The SDK calls a handler on a background dispatcher (Dispatchers.Default); switch to the main thread for anything that touches the UI. status runs each time a flow is configured and each time its activity resumes, so keep it cheap and never prompt from it. The activity is the one the flow is shown above, and Android can recreate it while request runs (a rotation): a handler that registers on it must register the same key again on the activity that replaces it to get the answer. request must return once the person answered: until then that flow's request waits, and so does any other flow's request for the same permission. A flow that is dismissed stops waiting, and the next flow asks again. A handler that throws reads as unavailable.

A status is a best guess on Android, which can't tell a permission never asked for from one the person denied for good ("don't ask again"). The SDK reads notifications as denied after it asked for them itself, or while Android suggests explaining the permission, and as not asked otherwise, also when your app asked itself and the person denied twice, or turned notifications off in the system settings; asking then is answered "not allowed" at once, without a prompt. A permission's status stays on the device unless the flow puts it into a tracked event's property or a person attribute.

Saved progress

The SDK saves a flow's own variables on the device, per person and per flow, for 90 days. Presenting the same flow again restores them, not the screen; inputs always come from your app. A Finish flow action, a successful purchase in a paywall, identify and reset clear them. A purchase in an onboarding flow doesn't.

Caching and offline

The SDK caches what each location shows for up to 7 days, so a flow shown once works offline. An answer is fresh for 5 minutes; after that, presenting asks Voidhash again and waits up to 500 ms for the reply, and when the app returns to the foreground the SDK refreshes the locations that are no longer fresh, one at a time. So a new deploy reaches an online device within about 5 minutes of its next presentation or foreground. Paywalls in your app explains when it asks Voidhash again. Downloaded flows are verified before they are kept. A build Voidhash withdrew is deleted from the device and never shown again, not even as the flow a location falls back to offline; with nothing else to show, presentFlow throws UNAVAILABLE. A flow you ship with the app is refused only once the device has heard of its withdrawal.

presentFlow gives a flow 15 seconds from the call to be ready to show. A flow that isn't ready by then is never shown: presentFlow throws UNAVAILABLE, and the download finishes in the background, so the next call shows the flow from the cache. A flow on screen has no time limit.

Download addresses

Flows, their images and their runtime modules download only over HTTPS from hosts on the internet. An address that names the device itself, a .local name or a private network is refused before anything connects to it, and so is a redirect to one; the flow then fails like any other download. Your baseUrl's host is trusted in every build. Debuggable builds also download over http from a server on the device (localhost, 127.0.0.1, ::1) and from the host of a baseUrl you set with http, such as http://10.0.2.2:8788 from an emulator, for local development.

A custom flowRenderer that downloads something a flow names, such as an image, asks FlowUrlPolicy first: request only the URL FlowUrlPolicy.permitted(url) returns, and follow a redirect only to the URL FlowUrlPolicy.permittedRedirect(from, location) returns. Both return null for an address a flow may not download. A renderer that presents flows without the SDK calls FlowUrlPolicy.allowLocalServers(context) to get the same exception for debuggable builds.

import com.voidhash.sdk.flows.FlowUrlPolicy

/** The URL a custom renderer requests for [url], reached by a redirect from [origin] if any. */
fun urlToRequest(url: String, origin: String?): String? =
    if (origin == null) FlowUrlPolicy.permitted(url) else FlowUrlPolicy.permittedRedirect(origin, url)

Loading screen

Apps show a loading screen while a flow loads from the network. When a flow has to wait for the network, the SDK shows it 0.4 seconds after the presentFlow call, at least long enough to be read, until the flow takes its place. A flow already on the device appears before then, without it. The loading screen has a progress indicator, which TalkBack announces as loading, and a cancel button, on your theme's android:colorBackground, inside the system bars. It follows the activity when Android recreates it, as the flow does.

The cancel button, or back, ends the presentation: presentFlow returns FlowResult.DISMISSED with wasShown set to false, which tells it apart from a flow the end user closed (wasShown is true then). wasShown is also false when your app dismissed a flow that was still loading. Analytics report $paywall_load_cancelled with cancelledBy: "end_user" only once Voidhash's answer named the flow; one left while its location was still being resolved reports nothing, since there is no flow yet to name.

TalkBack reads the voidhash_flow_loading string, "Loading". The SDK ships it in English only; define it in your app's translated resources to translate it.

To show your own view instead, or none, configure the renderer:

import com.voidhash.ui.FlowLoading
import com.voidhash.ui.FlowViewRenderer

VoidhashOptions(
    flowRenderer = FlowViewRenderer().apply {
        loading = FlowLoading.Custom { context, cancel -> MyLoadingView(context, onClose = cancel) }
        // Or keep your own screen until the flow is ready:
        // loading = FlowLoading.None
    },
)

Your view fills the screen edge to edge, so keep its content inside the system bar insets.

Ship a flow with the app

On a first launch without a connection, or while Voidhash can't be reached, a location the device has never loaded shows nothing. To show a flow then, ship it in the app's assets: write the location's files into src/main/assets/voidhash-flows/ with the Voidhash CLI:

voidhash location bundle onboarding --out app/src/main/assets/voidhash-flows

It writes two files per location: onboarding.json, the location's answer, and onboarding.vhfp, the flow's build, checked against the answer's SHA-256. The answer is what a new anonymous person is shown: never a pin or a targeting rule, for a location with an A/B test its control arm, and while the build the location shows is withdrawn, the earlier build apps are served instead. If you present the location with a revision, pass it: --revision onboarding=2.

Run the command in your release build step. The SDK stops showing the files after their notAfter, 90 days from the day the command ran, not from your release: if you release less often than that, new installs show nothing offline after the 90 days unless you pass a later --not-after or --no-expiry. More on the command.

The SDK reads the files off the main thread, and shows the shipped flow only when it has no answer for the location and couldn't reach Voidhash (no connection, a timeout or a server error). It never shows it:

  • when Voidhash answered, a rejected key or another error included;
  • when Voidhash answered earlier that the location shows nothing, however long ago (that answer is kept per person and SDK build);
  • after notAfter, when the file doesn't match the build's SHA-256, or when the app presents another revision of the location;
  • when the device has heard that Voidhash withdrew that build.

A withdrawal reaches a device only with an answer, so on a first launch offline the shipped build is shown however old it is, until its notAfter. Keep notAfter close and bundle again when you deploy. An old shipped flow can offer a product you've since unlinked in Voidhash: the purchase goes through in the store but grants nothing until you link the product again.

Purchases from a shipped flow name the location and build in the answer, marked source: "bundled", and its analytics events carry packageSource: "bundled". Every flow's events carry packageSource: network, cache or bundled.

A flow's images are kept on the device too, up to 64 MB, so a cached flow shows them while their host can't be reached. The SDK fetches them ahead when it preloads a location or loads its flow, except on a metered connection such as cellular data. Only images of up to 10 MB from https addresses on the internet are loaded, never from the device itself or its local network, nor from an address with a user name or password, and a redirect is followed only to such an address. An embedded data: image shows when it is at most 10 MB. A debuggable build also loads images from the development server it is configured with. Your Voidhash server, the one baseUrl names, is always allowed over https whatever its address, and so are images uploaded to your project. An image uploaded to your project shows only when its bytes are the ones recorded when it was uploaded: one that differs fails like any other image, isn't kept, and is reported once per image and build each time the app runs as $paywall_image_integrity_failed. Only PNG, JPEG, GIF and WebP images are kept. A kept image isn't downloaded again, so publish changed artwork under a new URL.

To make a flow available offline before its first presentation, list its location in preloadLocations:

VoidhashOptions(
    preloadLocations = listOf("onboarding"),
)

A location is preloaded for the revision in flowRevisions, so set it for the locations you preload.

To find out what a location would show without presenting it, call resolvePaywall("onboarding"). It returns a ResolvedPaywall with paywallId, releaseId and version, or null when nothing is assigned or no renderer is configured. resolvePaywallState adds the cache freshness. Handing the paywall to your app counts the person in the A/B test that chose it, as presenting would, even when you only look at what is assigned; see Analytics and revenue.

Analytics and revenue

Each presentFlow call that gets a flow to show records exactly one of these, with loadDurationMs (from the call until then). Every event about a flow, its own included, carries packageSource once its build is loaded, so a load that fails before then has none: network, cache or bundled (a flow you ship with the app):

EventWhenPropertyValues
$paywall_viewedThe flow is drawn and running.Also flow_screen_index and flow_screen_name, and productsUnavailable: true when it shows without its store products
$paywall_load_failedIt failed before it was viewed.reasonpackage_download_failed, package_integrity_failed, package_unsupported, runtime_download_failed, render_failed, timeout, other
$paywall_load_cancelledIt was given up on before it was viewed.cancelledByapp, end_user (the loading screen's cancel button or back)

A viewed flow then records how it ended, unless the app is terminated first:

EventWhenPropertyValues
$paywall_completedThrough its end step, or a purchase or restore that ends it.completionend_step, purchase, restore
$paywall_dismissedAny other way: its close button or the back button, your app, or an error.reasonclose, app, error

A purchase in a flow that carries on, such as an onboarding flow, isn't an ending. The back button goes back in the flow and, from its first screen, closes it as its close button does, so it's recorded as close; the system value other platforms send for a system gesture practically never occurs on Android. Your app giving up includes dismissFlow, a cancelled coroutine, another presentFlow, shutdown and the activity finishing. A flow shown again after a rotation or another configuration change is the same presentation, also when the rotation came while it was loading; a retry is a new one. A presentFlow call that throws NOT_ASSIGNED, RENDERER_MISSING or DISABLED, or UNAVAILABLE because the location was never loaded and Voidhash can't be reached, records nothing, and neither does preloading. The events are queued like any other: one recorded offline is sent later, once. Without analytics consent none of them is recorded.

These events, the events from Track event and each screen of a flow, recorded as a screen view with flow_screen_index, carry paywall_location, paywallId, paywallLocationId, paywallShowingId and paywallReleaseId. An intercepted close records $paywall_close_intercepted.

A person is counted in the A/B test that chose a location's flow when presentFlow shows, fails or gives up on it, or when resolvePaywall or resolvePaywallState hands it to your app, which records $paywall_handed_off each time. Preloading and the SDK's own refreshes count nobody.

A purchase made in a flow credits its revenue, renewals included, to the location, paywall, build and A/B test arm. Purchases made outside a flow and restores aren't credited to a paywall.

Next steps

Something wrong or missing on this page? Tell us by email or on Discord.