Android SDK (Kotlin)
The native Android SDK provides analytics, sessions, logs, handled errors, crashes, and real-user monitoring (RUM). It writes accepted records to app-private storage and delivers them in the background.
Install with Gradle
Configure the repository supplied with your selected AppPortal SDK distribution, then keep
Google and Maven Central for Android and public dependencies. In settings.gradle.kts, merge
these entries into your existing dependency repositories:
dependencyResolutionManagement {
repositories {
google()
mavenCentral()
maven { url = uri("<sdk-maven-repository>") }
}
}
Replace <sdk-maven-repository> with that distribution’s repository URL; do not use a private
source checkout URL as a Maven repository. Add the telemetry artifact to your application module’s
build.gradle.kts, replacing <sdk-version> with the exact version from the same distribution:
dependencies {
implementation("io.appportal:telemetry:<sdk-version>")
}
Messaging and Location are separate, optional artifacts. Add them later only when the app is ready to adopt Messaging or Location.
Initialize in Application
Start AppPortal once immediately after super.attachBaseContext(base) in your Application,
before other app initialization. This initializes storage, crash capture, and lifecycle observation
before Application.onCreate(), content providers, and the first Activity:
package com.example.store
import android.app.Application
import android.content.Context
import io.appportal.telemetry.AppPortal
import io.appportal.telemetry.AppPortalConsentState
class StoreApplication : Application() {
override fun attachBaseContext(base: Context) {
super.attachBaseContext(base)
AppPortal.start(this, "<app-credential>") { options ->
// Optional: use your application's chosen user identifier.
options.initialUserId = "customer-42"
// Set this only when your consent policy permits collection immediately.
options.initialConsentState = AppPortalConsentState.Granted
}
}
}
Register the application class in AndroidManifest.xml:
<application
android:name=".StoreApplication"
android:label="@string/app_name">
<!-- activities -->
</application>
The default consent state is Pending. A stored decision wins on later launches; call
AppPortal.grantConsent() or AppPortal.revokeConsent() when the user changes that decision.
Start with automatic telemetry
After initialization and consent, the SDK creates the session and observes Activity lifecycle. Background and resume the app, then open its session to see the available lifecycle context. Supported unhandled failures are collected by the crash integration; report exceptions your code catches explicitly.
Cold-start timing begins at AppPortal.start, before SDK configuration and storage setup, and
ends at the first Activity resume. The SDK reports cold-start automatically,
including application initialization between those boundaries. Observed returns from background
produce warm-start; duplicate activation and interrupted resumes do not add misleading durations.
Captured fatal exceptions during a pending start report it as failed. These measure native
activation, not first-frame rendering. No manual timer or startup event is needed.
Connect navigation once
For apps using Jetpack Navigation, attach one
destination-change listener
to the NavController that owns your screens. Use your existing controller and navigation graph IDs:
import androidx.navigation.NavController
import io.appportal.telemetry.AppPortal
val screenNames = mapOf(
R.id.catalog to "catalog",
R.id.checkout to "checkout"
)
val telemetryNavigation = NavController.OnDestinationChangedListener { _, destination, _ ->
screenNames[destination.id]?.let { AppPortal.trackScreen(it) }
}
navController.addOnDestinationChangedListener(telemetryNavigation)
Retain the listener and remove it with removeOnDestinationChangedListener when its owner is
destroyed or the controller is replaced. Replace the map with your app’s destinations. With
another navigation system, make the same call from its central route-change callback. Use stable
screen names and exclude arguments; do not also report each screen from individual pages.
Add your own events and logs
Use stable names and bounded property values so dashboards remain useful as the app grows:
import io.appportal.telemetry.AppPortal
import io.appportal.telemetry.AppPortalLogLevel
AppPortal.trackEvent(
"checkout.completed",
properties = mapOf(
"plan" to "growth",
"paymentMethod" to "card"
),
measurements = mapOf("value" to 49.00)
)
AppPortal.log(
AppPortalLogLevel.Information,
"Order submitted",
category = "commerce",
properties = mapOf("fulfillment" to "delivery")
)
Set identity after sign-in, and clear it during sign-out:
AppPortal.identify("customer-42")
AppPortal.setContext("storeId", "west-12")
// On sign-out:
AppPortal.clearUser()
Measure RUM and capture failures
import io.appportal.telemetry.BreadcrumbLevel
import io.appportal.telemetry.RumKind
val span = AppPortal.startSpan(
"catalog.refresh",
RumKind.NetworkRequest
)
try {
catalog.refresh()
span.finish(succeeded = true, httpStatusCode = 200)
} catch (error: Exception) {
span.finish(succeeded = false)
AppPortal.addBreadcrumb(
"Catalog refresh failed",
category = "catalog",
level = BreadcrumbLevel.Warning
)
AppPortal.captureError(error, mapOf("operation" to "refresh"))
}
Android Activity lifecycle is observed automatically. Record application-specific navigation with
trackScreen, and use ScreenLoad, NetworkRequest, or Custom spans for operations whose
duration matters to users.
Accepted records are written to app-private durable storage before background delivery. Offline retry and later-launch recovery are SDK responsibilities; applications do not call flush or close.
Follow the session
The SDK associates events, logs, errors, and timings with the current session. Lifecycle observations add foreground/background context. Automatic crash collection covers supported unhandled failures; use the explicit error API above for failures your app catches and recovers from.
Run a test flow, then open Sessions in the Dashboard and select the run’s Session story. Its timeline connects the available signals. Continue with Investigate an app session for the full workflow.
Observe OkHttp requests deliberately
Install one interceptor on the OkHttp client your application actually uses, after AppPortal starts:
import io.appportal.telemetry.AppPortalOkHttpInterceptor
import okhttp3.OkHttpClient
val http = OkHttpClient.Builder()
.addInterceptor(AppPortalOkHttpInterceptor())
.build()
It observes that client’s calls through response headers without consuming bodies or modifying credentials. It does not instrument every HTTP stack. The default request context is normalized method/origin; paths, query strings, headers and bodies are not supplied to the request-name mapper. Keep one instrumentation owner for each request path instead of reporting a duplicate manual span.
Configuration, privacy and offline recovery
Configure the existing AppPortal.start options at the native root:
| Option | Default / behavior |
|---|---|
initialUserId |
No user ID; use one exact opaque ID and clear it on sign-out |
initialConsentState |
Pending; a stored decision wins on later launches |
maxQueueSize / maxBatchSize |
10,000 queued records / 50 per batch; bounded storage can drop records |
captureUnhandledExceptions |
Enabled; explicit handled errors do not prove JVM/native fatal recovery |
captureAppStarts |
Enabled; native activation timing is not first-frame rendering |
captureNetworkRequests |
Enables the explicitly installed OkHttp interceptor |
endpoint |
Default Client API endpoint; HTTPS for remote hosts, narrowly allowed local/emulator development endpoints |
beforeSend |
Optional pre-persistence filter; keep capture/worker-thread callbacks short and thread-safe |
Collection consent, Android notification permission and channel communication consent are separate. Do not place secrets or personal profiles in event/log properties. A privacy callback is not a guarantee that arbitrary application data is safe to collect.
The SDK owns its app-private journal and retries. A bounded queue, abrupt process termination and an unsupported fatal path do not promise delivery. Keep the same installed test app for recovery; do not clear storage, rotate the credential or add a required flush/close ceremony to force a result. Follow known-event and crash verification, then troubleshooting if the result is unavailable. For FCM registration and Message Center, use Messaging with the matching optional artifact, device permission, channel configuration and authenticated user/installation binding.
Next steps
- Review consent and reliable delivery.
- Compare the Apple, .NET, and Flutter SDKs.