Integrate an SDK · Android

Android SDK

Native Kotlin SDK with a Java-friendly API, an instrumentation replay runner, and a demo shop app. Capsules carry sdk.name: bugcapsule-android and runtime.name: android.

Coordinates
io.github.bugcapsule:<artifact>:0.4.1
Requirements
minSdk 23 · Java 17 bytecode · libraries compiled against SDK 36 (README states compileSdk 34+)
Toolchain
AGP 8.13, Kotlin 2.2.20
Distribution
Maven Central, under io.github.bugcapsule.

HTTPS on older devices: minSdk 23 covers the SDK runtime. The hosted API currently uses a Let’s Encrypt certificate chain. An unpatched Android 6 emulator cannot validate that chain and reports Trust anchor for certification path not found; capture and replay work locally, but remote configuration and uploads remain offline. Test the backend’s certificate chain on your oldest supported device. Android 7.1.1+ includes ISRG Root X1 according to Let’s Encrypt’s compatibility documentation. Do not disable certificate or hostname validation.

Artifacts

ArtifactPackageWhat it does
bugcapsule-androiddev.bugcapsule.androidCore: capsule codec and validator, recorder, redaction, request keys, remote config, outbox, capture (lifecycle, pointers, Back key, failures, crashes), replay engine, Views helpers, SharedPreferences and DataStore checkpoints, state serializers (ViewModels too)
bugcapsule-okhttpdev.bugcapsule.okhttpOkHttp 4 capture and deterministic replay (Retrofit works through it); OkHttp WebSockets (below)
bugcapsule-navigationdev.bugcapsule.navigationJetpack Navigation route events, checkpoint and restore
bugcapsule-composedev.bugcapsule.composeCompose helpers: semantic actions, tracked text, navigation effect
bugcapsule-android-replaydev.bugcapsule.android.replayandroidTest only. BugCapsuleReplayRunner (an AndroidJUnitRunner) and BugCapsuleReplayTest

1. Gradle setup

Add Maven Central to your repositories and pin all BugCapsule modules to the same version:

dependencyResolutionManagement {
    repositories {
        google(); mavenCentral()
    }
}
android {
    defaultConfig {
        // The replay runner must be the instrumentation runner of the app's androidTest APK.
        testInstrumentationRunner = "dev.bugcapsule.android.replay.BugCapsuleReplayRunner"
        // The CLI passes -PbugcapsuleGitSha=<sha> so capsules and replays carry the build's commit.
        // Pass it in every other build too, release included: -PbugcapsuleGitSha=$(git rev-parse HEAD).
        buildConfigField("String", "BUGCAPSULE_GIT_SHA",
            "\"${providers.gradleProperty("bugcapsuleGitSha").getOrElse("")}\"")
        // The SDK token comes from the environment / CI secrets, never from sources.
        buildConfigField("String", "BUGCAPSULE_TOKEN",
            "\"${providers.environmentVariable("BUGCAPSULE_SDK_TOKEN").getOrElse("")}\"")
    }
    buildFeatures.buildConfig = true
}

dependencies {
    implementation("io.github.bugcapsule:bugcapsule-android:0.4.1")
    implementation("io.github.bugcapsule:bugcapsule-okhttp:0.4.1")
    implementation("io.github.bugcapsule:bugcapsule-navigation:0.4.1")
    implementation("io.github.bugcapsule:bugcapsule-compose:0.4.1")        // if you use Compose
    implementation("io.github.bugcapsule:bugcapsule-ndk:0.4.1")            // native crash events (optional)
    implementation("io.github.bugcapsule:bugcapsule-sqlite:0.4.1")         // SQLite / Room spans (optional)
    androidTestImplementation("io.github.bugcapsule:bugcapsule-android-replay:0.4.1")
    // Only if you checkpoint Preferences DataStore:
    implementation("androidx.datastore:datastore-preferences:1.1.1")
}
!

The library modules ship no manifest. Your app must declare android.permission.INTERNET (uploads and the replay socket).

2. Connect with your SDK token

i

SDK tokens and the status API are included in these releases. Use the SDK token from your dashboard for a new integration. Existing explicit API URL and ingest key configuration remains supported.

Generate an SDK token in the dashboard (Project Settings › Keys › SDK tokens; it is shown once). It carries your BugCapsule address and an upload-only credential, so it is the only value the app needs:

class ShopApp : Application() {
    override fun onCreate() {
        super.onCreate()
        BugCapsule.init(this, BuildConfig.BUGCAPSULE_TOKEN)
    }
}
BugCapsule.init(this, BuildConfig.BUGCAPSULE_TOKEN);

Call it first in Application.onCreate, not from a ContentProvider or App Startup initializer: in replay the runner restores storage right before Application.onCreate. BUGCAPSULE_TOKEN is the buildConfigField from step 1; a string literal works too, since the token ships inside the app anyway.

That is the whole connection: capsule capture and monitoring (errors, ANRs, sessions, screen tracing) start automatically, the configuration is fetched in the background, and app version and build come from the package info. The token is client-visible: it can only fetch the project's SDK configuration and upload Capsules and events. It never reads data. Hosted and self-hosted BugCapsule work the same way. Never put a bcs_ secret key in an app.

init never throws, never blocks on the network and never stops the app from starting. A token that can't be used (empty, damaged, a bare key pasted instead of the token, or a newer token version) logs one line under the BugCapsule tag with what to do, and the app runs without uploads.

Check the connection

val status = BugCapsule.status()
Log.i("Shop", "BugCapsule ${status.connection.state.code}: ${status.connection.message ?: "ok"}, missing ${status.instrumentation.missing}")

status.connection has state, source (TOKEN / BACKEND), apiUrl, reason, message and two separate confirmations: configFetchedAt (Configuration fetched: address, token and network are right) and firstEventAcceptedAt / firstCapsuleAcceptedAt (First event or Capsule received: captured data reached your project). The dashboard shows the same two confirmations during onboarding and in the SDK token list. Neither proves complete replay instrumentation; that is status.instrumentation (recording, network, navigation, appState, nativeCrashes, frameworks, integrations, missing).

state (.code)Meaning
NOT_CONFIGURED (not_configured)No token and no backend: capsules stay on the device
INVALID_TOKEN / UNSUPPORTED_TOKEN_VERSIONThe token can't be used (message says why); the app runs without uploads
CONNECTINGConfigured; the configuration has not arrived yet
CONNECTEDBugCapsule answered the configuration request
OFFLINENo network, a timeout or a server error. Data waits in the bounded outbox and is retried with backoff; the app is unaffected
REJECTEDThe credential was refused; reason is token_revoked, token_expired, token_unknown (or key_unknown_or_revoked for an ingest key) and message says what to do. Capture and uploads stop for this app session. Ship a build with a current token
DISABLEDenabled(false), capture switched off for the project, or a replay run

3. Add the progressive adapters

The token proves connectivity; replay also needs the app's inputs. Add the artifacts from step 1 and pass their integrations. Any you skip show up as missing in BugCapsule.status(). Steps 4–8 below wire each one.

AdapterGives replaystatus().instrumentation
bugcapsule-okhttp (BugCapsuleOkHttp)Network fixtures (OkHttp, Retrofit)network
bugcapsule-navigation (BugCapsuleNavigation)Routes, back stack restorenavigation
BugCapsuleSharedPreferences / BugCapsuleDataStore, registerState / registerViewModelApp state in checkpointsappState (app_state in missing)
bugcapsule-compose helpersSemantic actions, tracked text, screensframeworks contains compose (after the first composition)
bugcapsule-ndkNative crash events, with a crash capsule when a recording journal is availablenativeCrashes
import dev.bugcapsule.android.BugCapsule
import dev.bugcapsule.android.BugCapsuleConfig
import dev.bugcapsule.android.core.CaptureMode
import dev.bugcapsule.android.core.EndpointRule
import dev.bugcapsule.android.storage.BugCapsuleDataStore
import dev.bugcapsule.android.storage.BugCapsuleSharedPreferences
import dev.bugcapsule.navigation.BugCapsuleNavigation
import dev.bugcapsule.okhttp.BugCapsuleOkHttp

class ShopApp : Application() {
    override fun onCreate() {
        super.onCreate()
        // First thing in Application.onCreate — not a ContentProvider or App Startup initializer:
        // in replay the runner restores storage right before Application.onCreate.
        BugCapsule.init(
            this,
            BugCapsuleConfig.builder()
                .token(BuildConfig.BUGCAPSULE_TOKEN)  // bcsdk.v1.… from the dashboard
                .mode(CaptureMode.QA)                 // default: DEBUG if debuggable, else PRODUCTION
                .gitSha(BuildConfig.BUGCAPSULE_GIT_SHA)
                .redactKeys("loyaltyId")
                .build(),
            listOf(
                okHttp,
                navigation,
                BugCapsuleSharedPreferences.builder().allowFile("shop_prefs").build(),
                BugCapsuleDataStore.builder().allow("settings").build(),
            ),
        )
    }

    companion object {
        val okHttp = BugCapsuleOkHttp(rules = listOf(
            // Fields that change on every run must not affect request matching.
            EndpointRule("POST", "/api/checkout", ignoreBodyFields = setOf("timestamp", "nonce"))))
        val navigation = BugCapsuleNavigation()
    }
}

A second init call is ignored with a warning. Setup errors are caught and the app runs without capture. Besides status(), the SDK exposes BugCapsule.isInitialized, isRecording, isReplaying, mode and session.

Java

BugCapsuleConfig config = BugCapsuleConfig.builder()
    .token(BuildConfig.BUGCAPSULE_TOKEN)
    .mode(CaptureMode.QA)
    .build();
BugCapsule.init(app, config, Arrays.asList(okHttp, navigation));
BugCapsuleViews.onClick(button, "cart.checkout", v -> viewModel.checkout());
BugCapsule.check("cart_total_non_negative", total >= 0, "total " + total);

Self-hosted or existing setups (advanced)

A self-hosted BugCapsule issues tokens that carry its own address, so the token setup above works unchanged. You can still configure the address and ingest credential explicitly; existing apps keep working as they are:

BugCapsuleConfig.builder()
    .backend("https://api.bugcapsule.com", BuildConfig.BUGCAPSULE_INGEST_KEY)   // bci_…, never a bcs_ key
    .build()

When both token and backend are set, the explicit backend wins and the SDK logs that the token was ignored. On an emulator, the token's address must be reachable from the device (a BugCapsule running on your own machine is 10.0.2.2, not 127.0.0.1); use an explicit backend otherwise.

4. Wire OkHttp

Add the SDK interceptor as the innermost application interceptor, after your own. Pass the same BugCapsuleOkHttp instance to init.

val client = OkHttpClient.Builder()
    .addInterceptor(AuthInterceptor())             // your interceptors first: they still run in replay
    .addInterceptor(ShopApp.okHttp.interceptor)    // BugCapsule last
    .build()
// or: ShopApp.okHttp.install(builder)
Constructor parameterDefaultNotes
rulesemptyEndpointRule(method, path, ignoreQuery, ignoreBodyFields, matchBodyFields). path supports :name segments and a trailing *.
ignoreQuery_ ts timestamp nonce cachebustQuery params dropped from every request key
ignoreBodyFieldsemptyJSON fields dropped before hashing, for every endpoint
maxBinaryBytes64 KiBBinary body prefix kept
maxKeyBodyBytes64 KiBLargest body hashed into the key
maxBodyWaitMs30 000After this a still-streaming body is recorded truncated
excludenullRequestFilter { request -> Boolean }: excluded calls record method, URL, status and timing only

In replay the interceptor answers from the capsule by request key + occurrence after the recorded latency, without calling chain.proceed. An unrecorded request throws ConnectException and reports network.unrecorded. Exchanges recorded as pending (in flight at a crash) are held open until the call is cancelled.

i

Because replay answers inside the interceptor, interceptors added after it, network interceptors, caching and cookies are not exercised in replay. One-shot and duplex request bodies are never read; they are keyed without a body hash.

5. Navigation

// After the graph is set, on the main thread:
ShopApp.navigation.attach(navHostFragment.navController)
val navController = rememberNavController()
BugCapsuleNavigationEffect(navController, ShopApp.navigation)

BugCapsuleNavigation(sanitizeLocation = LocationSanitizer { it.replace(Regex("/orders/\\d+"), "/orders/:id") }) rewrites locations that contain secrets or ids. Route events carry source: "navigation"; {route, backStack} is snapshotted in periodic checkpoints and restored by navigating. Only String, Number and Boolean arguments are kept (Parcelables are not restored).

6. Actions and tracked text

Semantic replay invokes registered actions by id and restores tracked text by id. It works even when the developer's screen differs from QA's.

import dev.bugcapsule.android.views.BugCapsuleViews

BugCapsuleViews.onClick(checkoutButton, "cart.checkout") { viewModel.checkout() }
BugCapsuleViews.trackText(couponField, "cart.coupon")
BugCapsuleViews.trackText(passwordField, "login.password")   // password input types are forced sensitive
import dev.bugcapsule.compose.*

val coupon = rememberTrackedText("cart.coupon")
TextField(value = coupon.value, onValueChange = coupon::onValueChange)

// Compose does NOT detect password fields: pass sensitive = true yourself.
val password = rememberTrackedText("login.password", sensitive = true)

Button(onClick = rememberBugCapsuleAction("cart.checkout") { viewModel.checkout() }) {
    Text("Checkout")
}

Lower-level API for custom widgets: BugCapsule.action(id, Runnable), registerAction(id, ActionHandler) / unregisterAction, recordAction(id, payload) and trackText(id, TextSetter, sensitive) which returns a TextTracker (onChanged(value), untrack()).

7. Assertions, errors and logs

BugCapsule.check("cart_total_non_negative", total >= 0, "total $total")
BugCapsule.fail("checkout_stuck", "spinner for 30 s")
try { … } catch (e: IllegalStateException) { BugCapsule.reportError(e) }
BugCapsule.log("legacy cache migrated", level = "warn")

A failure writes a capsule automatically: 300 ms after the failure (crashes immediately), at most maxCapsulesPerSession (3) per session, one per failure signature. Manual capture() calls count toward the same quota.

What is captured automatically

8. State and storage

// ViewModel state in periodic checkpoints, restored in replay (auto-unregistered when the VM clears)
BugCapsule.registerViewModel(this, "cart", { state.toJson() }) { value -> state = CartState.fromJson(value) }

// Any other app state
BugCapsule.registerState("session", { sessionStore.snapshot() }) { sessionStore.restore(it) }
BugCapsule.reportState("cart")          // diagnostic `state` event (not replayed)

Storage is allowlist only; nothing is read unless you name it:

BugCapsuleSharedPreferences.builder()
    .allowFile("shop_prefs")                 // every key of a file
    .allow("settings_prefs", "feature.")     // keys with a prefix
    .deny("settings_prefs", "feature.secret")
    .build()

BugCapsuleDataStore.builder()                // reads files/datastore/<name>.preferences_pb
    .allow("settings")
    .build()

Both are restored by the replay runner before Application.onCreate. Periodic checkpoints (every 30 s) are used only when the session outgrows the 5-minute / 20,000-event window; otherwise replay starts from the launch checkpoint and re-executes the whole session.

9. Deterministic hooks and manual capture

val nonce = BugCapsule.random().nextInt()     // seeded per session; same seed in replay
val now = BugCapsule.currentTimeMillis()      // recorded wall clock in replay

BugCapsule.capture(note = "QA: total looks wrong")   // Future<CaptureResult?>
BugCapsule.flushUploads()
BugCapsule.refreshRemoteConfig()
BugCapsule.savedCaptures()                    // List<File>, newest 20

A manual capture with no failure gets a blocking failure.assertion gap and is ineligible: stored and inspectable, never counted in the reproduction rate.

WebSockets and native SDKs

i

Available from 0.4.1-beta.5. Capsules with WebSocket or adapter traffic are written as capsule spec v2, which older CLIs reject: update the CLI everywhere it runs, CI included, before you turn these on. Other capsules stay v1.

OkHttp WebSockets

Sockets are captured when the app opens them through BugCapsuleWebSockets (in bugcapsule-okhttp). Pass the instance to BugCapsule.init's integrations and use its factory where you call newWebSocket:

val webSockets = BugCapsuleWebSockets()          // add it to BugCapsule.init's integrations
val sockets: WebSocket.Factory = webSockets.factory(client)
val ws = sockets.newWebSocket(Request.Builder().url("wss://quotes.example.com/v1/stream").build(), listener)
// or: webSockets.newWebSocket(client, request, listener)

Native adapter API

Other SDKs (location, auth, databases, payments) need an adapter. Implement NativeAdapter (identity, operations, payload policy), wrap the SDK in a small class of your own that routes its calls and subscriptions through NativeInteractions.call / subscribe, and pass the NativeInteractions to init:

class LocationAdapter : NativeAdapter {
    override val id = "example.location"            // the adapter id capsules and capture settings use
    override val version = "1.0.0"
    override val schema = 1
    override val operations = setOf("location.last", "location.updates")
    override val tested = mapOf("example-location-sdk" to "2.1.0")
}

val location = NativeInteractions(LocationAdapter())   // add it to BugCapsule.init's integrations
val provider: LocationProvider = BugCapsuleLocationProvider(realProvider, location)

// In BugCapsuleLocationProvider, your wrapper around the real SDK:
bridge.call("location.last", null, callback) { cb -> real.lastLocation(cb) }
bridge.subscribe("location.updates", mapOf("intervalMs" to 1000), subscriber) { s -> real.requestUpdates(s) }

Check an adapter in a plain JVM unit test with NativeAdapterConformance (testImplementation("io.github.bugcapsule:bugcapsule-android-replay:…")). It records a scripted session, replays it offline and fails on any divergence, on SDK use during replay, and when an unsupported operation doesn't produce an explicit gap. The SDK repository has a complete example location adapter and its test.

private val conformance = NativeAdapterConformance({ LocationAdapter() })

@Test fun adapterConforms() {
    conformance.assertConforms(NativeAdapterConformance.Scenario { ctx ->
        val sdk = FakeLocationSdk(ctx)                        // reports every SDK use with ctx.sdkUsed(...)
        val provider = BugCapsuleLocationProvider(sdk, ctx.bridge)
        provider.lastLocation(observer(ctx, "last"))           // a callback that reports results with ctx.observe(...)
        ctx.advance(40)
        if (!ctx.replaying) sdk.answer(Location(52.37, 4.89, 12f, 1_000))
        ctx.advance(10)
    })
}

@Test fun unsupportedOperationsProduceGaps() {
    conformance.assertUnsupported("location.geofence", mapOf("radiusM" to 100))
}

Replay and limits

Configuration reference

BugCapsuleConfig.builder()…build() (also toBuilder()).

Builder methodDefaultNotes
appVersion, appBuild, appId, appName, flavorpackage infoversionName, versionCode, packageName, label
modeDEBUG if debuggable, else PRODUCTIONOnly sampling depends on mode: debug and QA always record
enabledtrueLocal master switch, read at init
token(token)noneThe SDK token (bcsdk.v1.…) from the dashboard: all a connection needs. Same as BugCapsule.init(app, token)
backend(url, ingestKey)noneThe advanced alternative to token, and wins over it. With neither, nothing is uploaded and capture settings aren't fetched. Never a bcs_ key
gitSha, gitDirtynullFallback: manifest meta-data dev.bugcapsule.GIT_SHA / dev.bugcapsule.GIT_DIRTY
stateSchemaVersion1A mismatch with a periodic checkpoint makes replay INCOMPATIBLE
checkpointIntervalMs30 000At least 1000
windowMs / maxEvents300 000 / 20 000Flight-recorder window
productionSampleRate0.1Remote sampleRate can only lower it
autoCaptureOnFailuretrue
maxCapsulesPerSession3Shared with manual captures
captureNetworkBodies / maxBodyBytesoff in production; on in debug/QA / 256 KiBANDed with the remote setting. Boolean?: off in production, on in debug/QA unless set; binary bodies need BugCapsuleOkHttp(captureBinaryBodies = true) (What's new)
collectionEnabled / savedCaptureMaxAgeMs / maxRetainedBytestrue / 7 days / 8 MiBconsent default, saved-capture expiry and in-memory recorder budget; see consent and local data
redactKeys, redactHeaders, redactPattern(regex), redactPatternsemptyAdded to the built-in rules
beforeRecordnullBeforeRecord { type, data -> data or null }, null drops the event
beforeCheckpointnullBeforeCheckpoint { integration, data -> … }
outboxLimitsOutboxLimits(10, 10 MiB, 7 days)Oldest evicted first
maxStaleConfigMs7 daysUploads need a config at most this old
ignoreErrornullErrorFilter { e -> Boolean }
label(key, value)emptyFree-form tags, scrubbed like text
maxSavedCaptures20

Replay

{
  "runtime": "android",
  "android": {
    "gradleDir": ".",
    "module": "app",
    "variant": "debug",
    "applicationId": "com.example.shop",
    "testApplicationId": "com.example.shop.test",
    "avd": "Pixel_6_2"
  },
  "timeouts": { "buildSeconds": 1200, "attemptSeconds": 120 }
}
bugcapsule run <id> -n 3            # expects REPRODUCED
bugcapsule verify <id> -n 3         # after the fix: FIXED only if every attempt is valid and clean
bugcapsule regress add <id> && bugcapsule regress run

All android.* keys are listed on the CLI page. What one attempt does:

  1. The CLI builds :<module>:assemble<Variant> and assemble<Variant>AndroidTest once, with -PbugcapsuleGitSha=<sha> -PbugcapsuleGitDirty=<bool> (or uses --apk/--test-apk).
  2. Per attempt: pm clear, adb reverse tcp:<port>, then am instrument -r -w -e bugcapsuleReplayUrl <url> -e class dev.bugcapsule.android.replay.BugCapsuleReplayTest <testAppId>/<runner>.
  3. BugCapsuleReplayRunner.onCreate (before Application.onCreate) fetches settings and capsule, refuses unless the app is debuggable, and restores SharedPreferences/DataStore.
  4. BugCapsule.init starts in replay mode. The test launches the launcher activity with ActivityScenario and runs the in-app engine: pointers via sendPointerSync (dp → px, scaled if the screen differs), Back via sendKeySync, actions and text on the main thread, lifecycle by moving the scenario (resumed→RESUMED, inactive→STARTED, paused→CREATED).
  5. The result goes to POST <base>/result and to instrumentation status bugcapsule_result=BUGCAPSULE_RESULT::{json}. A replayed crash reports synchronously from the crash handler before the process dies.

From 0.4.1-beta.5, pointer events include soft-keyboard visibility. The runner restores that state before each gesture so a keyboard left open does not intercept touches intended for the app. If synchronization fails, replay reports a divergence. Older capsules keep their original behavior; capture again with this version to include keyboard state.

Strategy AUTO uses pointer replay when the screen matches or no actions exist, otherwise semantic. Idle gaps over 1.5 s shrink to 0.3 s; recorded network latency is never shortened.

✓

Production protection. Replay can only be armed from an Instrumentation (the runner ships in the androidTest APK only) for a debuggable app. There is no intent, deep link, URL, push or file path into replay.

The emulator must be unlocked once after boot. AVDs with a screen-lock PIN cannot be unlocked by the CLI. --device picks a running device (serial, AVD name or model) or an AVD to boot; an emulator the CLI booted is shut down afterwards.

Uploads and capture settings

Demo app

examples/demo: a Views + Compose shop (Retrofit on OkHttp, an in-process FakeShopServer interceptor below the SDK, Jetpack Navigation, allowlisted SharedPreferences and DataStore, CartViewModel registered as state).

BugTriggerWhy replay needs BugCapsule
Data-dependent: item with price: null1 in 4 carts; CheckoutThe recorded server response
Negative totalCoupon SAVE100 on a cart under 100check("cart_total_non_negative") + tracked text
Race: recommendations before profile"Refresh home" (~1 in 4)Recorded response latencies
Legacy cart cache"Simulate upgrade from v0.9", restart, open cartThe launch checkpoint restores shop_prefs
BUGCAPSULE_TOKEN=bcsdk.v1.… ./gradlew :demo:assembleDebug     # the token enables uploads
# Self-hosted / advanced: BUGCAPSULE_INGEST_KEY=bci_… with -PbugcapsuleBackendUrl=https://api.bugcapsule.com

# Isolated fix toggle, no tracked source change:
BUGCAPSULE_ANDROID_GRADLE_ARGS=-PbugcapsuleDemoFix=race bugcapsule verify <id> -p examples/demo

Only race keeps the recorded request sequence. price and legacy change which requests the app makes, so verifying those is (correctly) INCONCLUSIVE with network.unrecorded.

Limitations

Monitoring and release readiness

This SDK also sends error events, release-health sessions, traces and feedback. Configure those separately from capsule recording using Monitoring, upload release symbols, and complete the integration checklist. For approved artifacts, versions and upgrade rules, start with Installation and upgrades.