# Mobile telemetry with OpenTelemetry

Use the standard OpenTelemetry SDKs to send mobile telemetry to Epok over OTLP/HTTP. Android 1.7.0 was verified on an Android 15 emulator on November 11, 2026. The iOS steps below were reviewed against source and have not been device-verified. Epok native packages remain early access and unpublished; this is the production integration route.

Time to first span: **~15 min**; Observe trial: **14 days, no card**; API key: [app.epok.cloud, then Settings, then API Keys](https://app.epok.cloud)

**Important.** Ask Epok support to enable mobile event mapping for your deployment before relying on crash and ANR alerts. The compatibility update is an opt-in rollout. Mobile apps must embed an **INGEST-ONLY** key: APKs and app bundles expose their credentials. In Settings, then API Keys, then Create key, select only ingest and deselect read and every other scope. Use it for YOUR\_INGEST\_ONLY\_KEY below. Never embed a default ingest+read key, a symbols key, or an admin key. The signed-in UI uses your session to resolve mappings; dedicated symbols:read keys are for trusted tools only.

## What this recipe covers

This recipe uses the community OpenTelemetry SDKs. Opt in to Android crash, ANR and jank capture by installing the pinned android-agent and initializing it after required consent, with both log and trace export and disk buffering as shown below. The older span-only setup cannot reliably report a fatal crash; recordException captures handled errors and does not install a crash reporter. Mobile event mapping in Epok is a separate deployment opt-in described above.

The [Epok Android SDK](https://epok.cloud/docs/install/android-rum) (epok-android 0.2.1) provides a consent-controlled wrapper with automatic crash and ANR capture. It and epok-ios 0.1.0 (EpokRum and EpokReplay) remain early access and unpublished; Swift Package Manager distribution is planned. See [native SDK installation](https://epok.cloud/docs/install/mobile-replay) and [mobile SDK status](https://epok.cloud/docs#mobile-sdk-status) for validation limits. iOS dSYM symbolication is not supported; Android R8 / ProGuard mappings are covered below. Session replay requires a separate library.

## OTLP/HTTP endpoints

Mobile exporters are configured in code. Send traces to https://ingest.epok.cloud/v1/traces and logs to https://ingest.epok.cloud/v1/logs over HTTPS with x-api-key on every request. Both accept OTLP protobuf. There is no gRPC (:4317) endpoint; use the HTTP exporter classes below. Metrics go to https://ingest.epok.cloud/v1/metrics (protobuf or JSON); see App metrics below.

## Android: pinned, verified setup

Use google() and mavenCentral() repositories. The agent installs app-start, Activity screen, crash, ANR and jank instrumentation. Several upstream modules are alpha; keep these versions pinned and test upgrades.

```
// Root build.gradle.kts: AGP 8.13.0, Kotlin 2.4.10; Gradle 8.13, JDK 17.
// app/build.gradle.kts:
android {
    compileSdk = 36
    defaultConfig { minSdk = 26 }
    buildFeatures { buildConfig = true }
    compileOptions { sourceCompatibility = JavaVersion.VERSION_17; targetCompatibility = JavaVersion.VERSION_17 }
    packaging.resources.excludes += "META-INF/versions/9/OSGI-INF/MANIFEST.MF"
}
dependencies {
    implementation("io.opentelemetry.android:android-agent:1.7.0")
    implementation("io.opentelemetry.android:core:1.7.0-alpha")
    implementation("io.opentelemetry.instrumentation:opentelemetry-okhttp-3.0:2.31.1-alpha")
    implementation("com.squareup.okhttp3:okhttp:5.4.0")
}
// Verified with SDK 36; upstream's AndroidX dependency otherwise requires SDK 37.
configurations.configureEach {
    resolutionStrategy.force("androidx.core:core:1.17.0", "androidx.core:core-ktx:1.17.0")
}
kotlin { compilerOptions { jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17) } }
```

```
import android.app.Application
import io.opentelemetry.android.OpenTelemetryRum
import io.opentelemetry.android.agent.OpenTelemetryRumInitializer

class App : Application() {
    lateinit var rum: OpenTelemetryRum
    override fun onCreate() {
        super.onCreate()
        rum = OpenTelemetryRumInitializer.initialize(this) {
            httpExport {
                baseUrl = "https://ingest.epok.cloud" // adds /v1/traces and /v1/logs
                baseHeaders = mapOf("x-api-key" to "YOUR_INGEST_ONLY_KEY")
            }
            resource {
                put("service.name", BuildConfig.APPLICATION_ID)
                put("service.version", BuildConfig.VERSION_NAME)
                put("app.version.code", BuildConfig.VERSION_CODE.toString())
            }
            diskBuffering { enabled(true) } // retains crash telemetry for the next launch
            disableMetrics() // This verified recipe covers logs and traces.
        }
    }
}
// AndroidManifest.xml: add INTERNET permission and android:name=".App" to application.
// Initialize in the main process, before the first Activity, after required consent.
// The SDK supplies os/device attributes and session.id; do not replace its resource.
```

Configure both logs and traces. Crashes, ANRs and jank are log events; a span exporter alone misses them. Keep disk buffering enabled, reopen the app after a test crash, and allow about a minute for buffered export.

The initializer's resource block adds release attributes to the SDK resource, preserving its OS/device metadata. If integrating through the lower-level RumBuilder API (core:1.7.0-alpha), merge the release resource with `.mergeResource(releaseResource)` instead of replacing it. This API alternative is source-reviewed; the initializer above is the emulator-verified route.

```
import io.opentelemetry.android.RumBuilder
import io.opentelemetry.android.config.OtelRumConfig
import io.opentelemetry.sdk.resources.Resource

val releaseResource = Resource.getDefault().merge(
    Resource.builder()
        .put("service.name", BuildConfig.APPLICATION_ID)
        .put("service.version", BuildConfig.VERSION_NAME)
        .put("app.version.code", BuildConfig.VERSION_CODE.toString())
        .put("os.name", "android")
        .build()
)
// Alternative builder customization; do not initialize a second SDK.
val builder = RumBuilder.builder(this, OtelRumConfig())
    .mergeResource(releaseResource)
// Configure log + trace exporters and disk buffering before building.
// A trace-only exporter does not deliver crash/ANR log events.
```

```
import io.opentelemetry.instrumentation.okhttp.v3_0.OkHttpTelemetry
import io.opentelemetry.api.trace.StatusCode
import okhttp3.OkHttpClient
import okhttp3.Request

val otel = (application as App).rum.openTelemetry
val calls = OkHttpTelemetry.builder(otel).build().createCallFactory(OkHttpClient())
// On a worker thread; use this Call.Factory for your app's requests:
calls.newCall(Request.Builder().url("https://YOUR_BACKEND/health").build())
    .execute().use { response -> response.body?.string() }

val tracer = otel.getTracer("checkout")
// Optional business screen span, in addition to the automatic Activity spans:
tracer.spanBuilder("screen.view").startSpan().apply {
    setAttribute("app.screen.name", "Checkout")
    end()
}
val span = tracer.spanBuilder("checkout.submit").startSpan()
try {
    span.makeCurrent().use { submitOrder() }
} catch (error: Exception) {
    span.recordException(error)
    span.setStatus(StatusCode.ERROR, error.message ?: "checkout failed")
} finally {
    span.end()
}
```

The instrumented HTTP client propagates trace context. Use it for requests to your instrumented backend to connect mobile and server spans. The local verification checked the client span; backend correlation requires your own server instrumentation.

## What you will see in Epok

- RUM spans for app starts, screens and HTTP requests, with app version and session identity.
- Handled exceptions on error spans, including the exception type, message and stack.
- Crash log events named app.crash or device.crash, a fatal level, an exception message, the original stack and the originating session.
- ANR events named device.anr or app.anr with an error level and main-thread stack. Jank events named app.jank have a warning level and frame/threshold attributes; the SDK does not attach an exception stack to jank.

Search for your service name, then event\_name and session\_id. Crash-free-session, ANR-rate and new-crash analysis use these fields. A single test crash proves delivery, not an alert: detectors require enough distinct sessions and baseline history. Session replay is a separate early-access capability and is not provided by this setup.

1. Run the app on a simulator/emulator and trigger an instrumented operation.
2. Open Traces and find your span under the configured service.name.
3. Open Explore to see error spans alongside backend traces; shared trace IDs correlate them when both HTTP client and backend are instrumented.

**Seeing no data?** Check the HTTP exporter protocol, x-api-key and service.name (otherwise data groups under unknown\_service). Keep the app foregrounded for ~30s or use the SDK's force-flush in testing to let the batch processor export. For buffered crashes, relaunch and allow about a minute as described above.

## iOS: source-reviewed OpenTelemetry route

**Verified on Android; iOS steps not yet device-verified.** Swift 2.4.1 supports OTLP/HTTP log and trace exporters. Add the packages and products below, retain the providers for the app lifetime, and supply os.name and a session ID. Add os.version and device.model.identifier when your app has those values.

```
// Package.swift: pin both packages; add their products to your app target.
.package(url: "https://github.com/open-telemetry/opentelemetry-swift.git", exact: "2.4.1"),
.package(url: "https://github.com/open-telemetry/opentelemetry-swift-core.git", exact: "2.4.1"),
// Products: OpenTelemetryProtocolExporterHTTP (opentelemetry-swift),
// OpenTelemetryApi and OpenTelemetrySdk (opentelemetry-swift-core).

import Foundation
import OpenTelemetryApi
import OpenTelemetrySdk
import OpenTelemetryProtocolExporterHttp
import OpenTelemetryProtocolExporterCommon

let config = OtlpConfiguration(headers: [("x-api-key", "YOUR_INGEST_ONLY_KEY")])
let resource = Resource(attributes: [
    "service.name": .string("com.example.shop"),
    "service.version": .string("1.0.0"),
    "os.name": .string("iOS"),
    "session.id": .string(UUID().uuidString) // one ID per app session, not per event
])
let traces = TracerProviderBuilder()
    .with(resource: resource)
    .add(spanProcessor: BatchSpanProcessor(spanExporter: OtlpHttpTraceExporter(
        endpoint: URL(string: "https://ingest.epok.cloud/v1/traces")!, config: config)))
    .build()
OpenTelemetry.registerTracerProvider(tracerProvider: traces)
let logs = LoggerProviderBuilder()
    .with(resource: resource)
    .with(processors: [BatchLogRecordProcessor(logRecordExporter: OtlpHttpLogExporter(
        endpoint: URL(string: "https://ingest.epok.cloud/v1/logs")!, config: config))])
    .build()
OpenTelemetry.registerLoggerProvider(loggerProvider: logs)

// Handled error example; never label a handled error as a fatal crash.
logs.get(instrumentationScopeName: "checkout").logRecordBuilder()
    .setEventName("exception")
    .setSeverity(.error)
    .setBody(.string("CheckoutError: checkout failed"))
    .setAttributes(["exception.type": .string("CheckoutError"),
                    "exception.message": .string("checkout failed")])
    .emit()
let tracer = traces.get(instrumentationName: "checkout", instrumentationVersion: "1.0")
let screen = tracer.spanBuilder(spanName: "screen.view").startSpan()
screen.setAttribute(key: "app.screen.name", value: "Checkout")
screen.end()
```

Optional: URLSessionInstrumentation in opentelemetry-swift creates HTTP client spans and propagates trace context. This optional integration has not been device-verified here.

This is manual instrumentation. The Swift SDK does not install a crash reporter, ANR/hang detector or jank monitor. A separate crash capture and persistence integration must supply device.crash/app.crash events, exception.type, exception.message and exception.stacktrace after restart. Do not attempt network export from a fatal signal handler. Native crash capture remains unverified here; Epok does not support iOS dSYM symbolication.

## Android release stack symbolication

Upload the R8 mapping from each minified release in CI. The build must enable minification to produce `app/build/outputs/mapping/release/mapping.txt`. Keep that file with the shipped artifact. Uploading a different mapping for an existing build key returns HTTP 409; retrying the same file is safe.

```
// app/build.gradle.kts: Android Gradle Plugin 8.x, minified release variants.
androidComponents.onVariants(androidComponents.selector().withBuildType("release")) { variant ->
    val output = variant.outputs.single() // For split APKs, choose the shipped output.
    val identity = layout.buildDirectory.file("epok/" + variant.name + ".json")
    tasks.register("write" + variant.name.replaceFirstChar { it.uppercase() } + "EpokIdentity") {
        outputs.file(identity)
        // Always evaluate the final variant values, including CI overrides.
        outputs.upToDateWhen { false }
        doLast {
            val file = identity.get().asFile
            file.parentFile.mkdirs()
            file.writeText(groovy.json.JsonOutput.toJson(mapOf(
                "platform" to "android",
                "app_id" to variant.applicationId.get(),
                "version_name" to output.versionName.get(),
                "version_code" to output.versionCode.get().toString()
            )))
        }
    }
}
```

The Android example exports exception spans from recordException as well as crash log events from the agent instrumentation. Open exception spans in Traces or crash stacks in RUM to retrace them. The emulator check used readable debug stacks; release symbolication needs its own minified-device validation. The Android setup and CI identity both use versionName plus versionCode. For versionName-only lookup, remove app.version.code from the Kotlin resource and version\_code from the Gradle identity; also omit app.build.id. Keep versionName unique per release build.

Upload is synchronous. Budget less than 100 seconds through the Cloudflare proxy: the earlier 100 MiB benchmark took 109.52 seconds including indexing, before the added PostgreSQL size-measurement pass. Large uploads can time out. Gzip reduces transfer size, not indexing time. For large maps use an operator-provided direct API origin with a longer timeout, or reduce map size; there is no universal safe byte threshold. curl --retry uses exponential backoff and honors Retry-After on 429; a timed-out identical upload is safe to retry. Do not treat a timeout as successful installation.

```
# CI only: EPOK_SYMBOLS_KEY has symbols:write scope. Never ship it in the APK.
# EPOK_API_URL is your API origin; EPOK_TENANT_ID identifies the project account.
./gradlew :app:assembleRelease :app:writeReleaseEpokIdentity
# With flavors, use the matching assemble/identity task and mapping/<variant>/ path.
QUERY=$(python3 -c 'import json, urllib.parse; print(urllib.parse.urlencode(json.load(open("app/build/epok/release.json"))))')
gzip -c app/build/outputs/mapping/release/mapping.txt > app/build/epok/mapping.txt.gz
curl --fail-with-body --silent --show-error --retry 5 --retry-max-time 600 \
  -H "Authorization: Bearer $EPOK_SYMBOLS_KEY" \
  -H "Content-Type: text/plain; charset=utf-8" \
  -H "Content-Encoding: gzip" \
  --data-binary @app/build/epok/mapping.txt.gz \
  "$EPOK_API_URL/api/v1/tenants/$EPOK_TENANT_ID/mobile/mappings?$QUERY"
# Inspect successful responses for warnings and evicted build identities.
# HTTP 409 mapping_capacity is an error: --fail-with-body prints its JSON and
# exits nonzero. Remove an unused mapping or request more capacity, then retry.
```

The key is Android + `service.name` + `service.version`, optionally with one of `version_code` or `build_id`. Without an explicit build key, versionName must be unique per release build; omit `version_code` from the upload identity for that mode. Lookups are exact; a request with a build key does not fall back to a version-only mapping. The Android setup above sets service.version and app.version.code from the app's BuildConfig. Ingest accepts these fields from resource, span, or log attributes, with record attributes taking precedence. For build IDs, emit `app.build.id` and upload the identical value. For apps using the Epok wrapper, automatic build-code metadata is planned for a later release; the wrapper does not add it automatically today.

Expand an exception stack in Traces to resolve it on read. Separately captured app.crash logs can also be retraced in RUM. Missing mappings and missing build identity remain visible, and the original stack remains available. Inline frames and ambiguous alternatives are shown; synthetic frames are retained and labeled. Unsupported R8 transformations produce warnings. This is not full compatibility with every R8 retrace extension.

Defaults: 128 MiB expanded per upload. Use gzip as shown to stay below Cloudflare's 100 MB request-body limit (compressed bodies must still fit that limit). The shared header is limited to 16 KiB; only its JSON metadata is retained, once per mapping. Each class is limited to 4 MiB; each resolve may load at most 8 MiB of selected class text. The packed class blob is capped at twice the upload limit. Busy compilers or resolve cache-miss memory budgets return HTTP 429 with Retry-After: 1; retry the same request. Per tenant/project, the index holds at most 200 builds and 1 GiB (1,073,741,824 bytes) of stored mappings. The charge is the compressed blob plus the measured PostgreSQL class-table/index footprint and retained header bytes. The measurement uses an isolated temporary table with the same row layout and indexes, excluding historical bloat and WAL. The measured 906,819-class fixture uses a 104,969,523-byte blob and a 214,925,312-byte isolated PostgreSQL footprint: 319,894,835 bytes per release. Three such releases total 959,684,505 bytes, within the default quota. Upload responses report bytes, index\_bytes and stored\_bytes. Upload builds a class index; resolve fetches only the required class ranges. Capacity eviction selects the oldest eligible build, protecting uploads younger than 30 days, each app's newest three builds, and builds referenced by crash rows in the last 30 days. Failed crash-history checks preserve builds. Operators can configure EPOK\_MOBILE\_MAPPING\_MAX\_PER\_TENANT, EPOK\_MOBILE\_MAPPING\_PROTECT\_DAYS, EPOK\_MOBILE\_MAPPING\_KEEP\_PER\_APP, and EPOK\_MOBILE\_MAPPING\_CRASH\_PROTECT\_DAYS. Evictions are listed in successful responses; HTTP 409 mapping\_capacity includes limits and a recovery action.

Create a separate symbols:write key in Settings, then API keys or the key creation API. Upload never accepts ingest scope alone. GET` /api/v1/tenants/{id}/mobile/mappings` lists builds with symbols:read scope or a session. DELETE the same path plus `/{mapping_id}` with an owner/admin session or a key with both read and write scopes to remove a bad mapping; the class index is removed too.

For custom tools, POST JSON to `/api/v1/tenants/{id}/mobile/mappings/resolve` with the same key fields and a `stack` string, using symbols:read scope or a signed-in session. Version codes and build IDs are strings. Requests accept up to 16 KiB and 100 stack lines, with at most 10,000 output frames (larger expansions return HTTP 413); the response includes raw lines, candidate frame chains, ambiguity flags, warnings, and a resolved method-frame count. Existing stored crash stacks are never rewritten.

## Scope and upstream references

Use HTTPS and the x-api-key header on /v1/logs and /v1/traces. This recipe disables metrics; metrics were not part of the Android verification. Real-device coverage, release symbolication and iOS device testing remain separate validation work.

[Android 1.7.0 source](https://github.com/open-telemetry/opentelemetry-android/tree/v1.7.0) [Swift 2.4.1 source](https://github.com/open-telemetry/opentelemetry-swift/tree/2.4.1) [Epok Android early access](https://epok.cloud/docs/install/android-rum) [Mobile replay early access](https://epok.cloud/docs/install/mobile-replay)

## One trace from the app to the backend

When your app's HTTP client is instrumented (URLSession / OkHttp above), it injects the W3C `traceparent` header into every request. If your backend is [instrumented for tracing](https://epok.cloud/docs/install/traces), its spans carry the **same trace\_id**, so "checkout is slow on the app" opens as a single trace: the tap in the app, the network call, and every backend span it caused, in one tree. A mobile error event and the backend exception it triggered land in the same place instead of two disconnected tools.

## App metrics from mobile

The mobile OTel SDKs' HTTP metric exporters emit OTLP **protobuf**, and Epok's `/v1/metrics` endpoint accepts it (OTLP JSON too), with the same `x-api-key` header as traces. Whether you give the base URL or the full URL depends on the exporter:

- **Swift** (`OtlpHttpMetricExporter(endpoint:)`) and **Java/Kotlin** (`OtlpHttpMetricExporter.builder().setEndpoint(...)`): the URL is used as given and nothing is appended. Use the full URL, `https://ingest.epok.cloud/v1/metrics`, the same way the Swift trace exporter above takes `/v1/traces`.
- **Environment-variable configuration** (`OTEL_EXPORTER_OTLP_ENDPOINT`): give the base URL, `https://ingest.epok.cloud`; the SDK appends `/v1/metrics`. A signal-specific `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT` is used as given, so it needs the full URL.

A 404 or 405 on the metric export means the path is missing or doubled.

The verified Android recipe disables metrics; the Swift snippet configures only logs and traces. To add counters, histograms or gauges, configure a metric provider/exporter separately. This path is outside the emulator verification. Or start with traces and errors only; they cover most mobile debugging and correlate with your backend out of the box.
