Record your mobile app
Send sessions from your iOS or Android app to On-Live with the official Datadog SDK — there is no separate Flamio mobile SDK.
Flamio On-Live records native apps as well as websites. You add the official Datadog RUM and Session Replay packages for your stack and point them at Flamio. App sessions land in the same Visits, issues, funnels and analytics as your website.
Supported stacks: iOS (SwiftUI and UIKit), Android (Jetpack Compose and Views), React Native, Flutter and Kotlin Multiplatform. A Capacitor or Ionic app draws its screens as a web page inside a WebView — record it with the web SDK instead, as Capacitor and Ionic apps describes.
Before you begin
- On-Live is enabled for the project and a project key exists — steps 1 and 2 of Install the web SDK. Those steps need the Editor, Admin or Owner role. The app uses the same project key as the website.
- You need access to your app's code and a way to ship a build. The packages and the config go into your app — Flamio cannot add them for you.
Open the mobile install
In the sidebar, under Flamio On-Live, click Setup.
- A project that covers a mobile app shows the card Install the mobile SDK, already open. A project that covers only an app shows it as step 3.
- A project that covers only a website keeps the same card folded under Have a mobile app?. Click it to open.
The card reads Point the official Datadog SDK at Flamio — no separate mobile SDK to install.
Pick your stack and copy the config
Select your stack on the tabs — iOS, Android, React Native, Flutter or Kotlin Multiplatform — and copy the config block. Right after you generate the key, the Setup page fills it into the block. The configs and their placeholders are also listed under Configs by stack.
Fill in the placeholders
The line under the block, Yours to fill in, names the values the config leaves to you — each stack names only the ones its own config carries:
your-api-host.com— your own backend host, so your app's requests appear in the replay.com.your.app— your app's bundle id (iOS) or package name (Android).currentUser— your signed-in user. Drop thesetUserInfocall if you do not identify users.
Install the packages and paste the config
In your app, install the Datadog RUM and Session Replay packages that the config imports. Paste each block where its comment says, and the rest where your app starts.
Allow your app id
Click Settings > Project settings. Under Allowed apps (Only these app ids can send sessions. Leave empty to allow any.), enter your bundle id or package name, one per line, and click Save.
Run the app
Build and run the app, and use it for a minute.
A mobile session ends only after about 30 minutes without activity, so it appears in Flamio On-Live > Visits about 30 minutes after your last tap.
The key ships inside your app
Anyone who unpacks your app can read the project key. Allowed apps is the only check on who may send sessions with it, so fill it in before you release the build.
Result
App sessions appear in Visits next to your web visits. To see only the app, set the Source filter to iOS or Android. Dead, rage and error taps on your app's controls become issues, the same as clicks on the web. So does a tap the app froze on — a UI Freeze, when the app stopped drawing for 700 ms or more as the visitor tapped.
What the app records
- Text and images are recorded as they appear. Only sensitive inputs — passwords, emails and phone numbers — are masked. The image-privacy and text-and-input-privacy lines in the config are what change either.
- A page inside a WebView is recorded by the web SDK, as a web visit of its own: install the web SDK on that page. The page must be served over https (or from localhost) — the web SDK does not start on plain http. Leave Datadog's WebView tracking off, as the config says.
- Crash reports are on for Android in every config. On iOS the iOS, React Native and Flutter configs leave them off — turn crash reporting on only if no other crash reporter runs in the app, and initialize Datadog before Firebase Crashlytics. With crash reporting on, an iOS app hang also shows its stack; with it off, a hang shows when it happened and how long it lasted.
- How the app launches and draws: launch times, frame rate, slow and frozen frames, memory, and the requests that took 2 s or more. The configs turn on Datadog's app hang reports from 0.7 s, the Android ANRs the app lived through and, on iOS, kills by the system: each is an error of its own kind in Issues > Errors. The Flutter config also turns on Flutter's own frame timings. On Android a Flutter app reports no frame rate or slow frames, because Datadog times the native window rather than Flutter's drawing; its freezes still show. It reports no launch time either: Datadog's Flutter plugin starts after the app's first screen opens, too late to see the launch. See See how fast your app is.
- In a native Android or Kotlin Multiplatform app, each press of the back button or the back gesture shows on the replay's timeline as Back, with the screen it was pressed on. An app that targets Android 16 (API level 36) shows none on Android 16 and later: Android no longer sends such an app the back key, which Datadog reads the press from.
- A failed or slow request also shows, when you expand it under Errors > Network in the replay, how long its DNS lookup, connection, TLS handshake, first byte and download took and the size of its body — each part Datadog measured. On Android, the config's OkHttp client times every part.
- An app sends no page speed, traffic source, UTM, browser or scroll depth. A project that covers only an app does not show Flamio ASA, the Page speed and Traffic & AI dashboard templates, Scroll depth by page, or dashboard charts of what only a website records.
- Android: the config lists each Datadog module with the version Flamio is tested with. Add every module at exactly that version: from 3.15.0, Datadog's Android SDK sends screen updates that On-Live does not read yet.
- React Native: the config pins Datadog's three React Native packages at the version Flamio is tested with. Install all three at exactly that version, with no
^inpackage.json: from 3.11.0 they bundle Datadog's Android SDK 3.15.0, which sends screen updates On-Live does not read yet. Each screen is named after its React Navigation route. A tap is named after thetestIDof the control, or of the closest element around it that has one: give each button its owntestID, or taps on different buttons of one screen count as taps on one control. A control with notestIDon it or around it is named by itsaccessibilityLabel. A minified Android release also needs the two-keeprules the config names inproguard-rules.pro; without them the app closes on its first screen. - Flutter: the config pins Datadog's Session Replay preview packages, which need Flutter 3.38 or later: on an older Flutter the app does not compile, so upgrade Flutter first or write to contact@flamio.org. Its
FlamioNavigationObservernames each screen after its route, so give your routes names. With go_router, use the config'sFlamioGoRouterViewsinstead: it names each screen by its full route path, such as/catalog/item/:id. A dialog, bottom sheet or menu stays part of the screen under it; a page pushed without a route name is named from what it shows. Images larger than about 800 × 800 pixels are recorded scaled down. A platform view (a native map, ad or WebView) records nothing in the app's replay. Wrap a map, an ad or a camera preview inSessionReplayPrivacy(hide: true): it shows as a Hidden box, and taps on it are not counted as taps on the screen under it. To mask a part that shows personal data, such as client names, phone numbers or a one-time code, wrap it inSessionReplayPrivacy(textAndInputPrivacyLevel: TextAndInputPrivacyLevel.maskAll). Requests made withdio,package:httpor a GraphQL client built on them are recorded with no extra setup; for gRPC, add Datadog'sDatadogGrpcInterceptor(packagedatadog_grpc_interceptor) to each gRPC client. Read each HTTP response's body: a response ended withdrain()does not appear as a request. Set any other error handler, such as Firebase Crashlytics' or Sentry's, beforeDatadogSdk.runApp: Datadog keeps it and passes every error on. A handler set inside therunAppcallback replaces Datadog's, and Dart errors no longer reach Flamio. - Kotlin Multiplatform: Android Compose and iOS SwiftUI or UIKit screens are recorded; Compose Multiplatform UI records as one blank shape. Name every screen yourself with the
startViewandstopViewcalls in the config — replacecatalogwith each screen's own name.
Capacitor and Ionic apps
A Capacitor or Ionic app draws its screens as a web page inside a WebView, so the web SDK records it. Skip the Datadog config: it records nothing inside a WebView.
Record an app with web SDK 0.11.0-beta.2 or later, which is in beta
Install it as @flamioai/web-sdk@beta. npm install @flamioai/web-sdk
still installs 0.9.0: with it, an app that turns on CapacitorHttp or
serves its page over http sends no sessions, and the visit lacks what
0.11.0-beta.2 adds.
Install the web SDK in the app
Add the web SDK to your app's web code and call Flamio.init at startup, as on a website — follow Install the web SDK. The app uses the same project key as your website. Pass your app's version as version, so Release impact compares app releases. If the same app also runs as a web app, pass its address as assetOrigin, such as assetOrigin: 'https://app.example.com': the replay then shows the images and fonts bundled with the app.
Allow the app's page
Capacitor serves the app's page from localhost on the device, or from the server.hostname your Capacitor config sets. If Settings > Project settings > Allowed domains lists your hosts, add that host and click Save.
App sessions appear in Visits as web visits — set the Source filter to Web — with your app's routes as pages. Dead, rage and error taps, forms and the console are recorded as on a website. Time the visitor spends in another app does not count as a pause.
What 0.11.0-beta.2 adds
- A tap that opens a window outside the WebView — the share sheet, a system dialog, the camera or photo picker, an in-app browser, a purchase screen — is not a Dead Click, and the time that window stays open does not count as a pause. The replay's timeline marks it as Native window.
- A visit the app opened from a link or a notification tap carries an Opened from a link or Opened from a notification mark on the timeline; a link's mark names its address.
- Scroll depth by page counts screens that scroll inside a container — the usual layout of an app.
- A tap the app answers 700 ms or more late is a UI Freeze.
- With
assetOriginset, the replay shows the images and fonts bundled with the app.
What an app's visit does not show:
- The windows outside the WebView themselves: the replay shows the page under them. With an earlier web SDK, a tap that opens one can read as a Dead Click, and the time it stays open counts as a pause.
- Images and fonts bundled with the app when
assetOriginis not set. The replay looks for them at the app's own address, which exists only on the device, so they show broken. - Native crashes, and the app start before the web page loads.
In a debug build, Capacitor writes each failed plugin call to the console — a share sheet the visitor closed, a canceled photo pick — and On-Live records them as console errors. A release build logs them only when loggingBehavior in your Capacitor config is 'production'. Set it to 'none' to keep a debug build out of your errors too.
Configs by stack
YOUR_KEY_HERE in each config is your project key from step 2 of the Setup page. The line under each config lists the other values to fill in.
iOS
import DatadogCore
import DatadogRUM
import DatadogSessionReplay
// A WebView's page is recorded by the Flamio web SDK as a web session of its
// own: add the web SDK to that page. The page must be served over https (or
// from localhost) — the web SDK needs a secure context and does not start on
// http. Do not enable Datadog WebView tracking.
// Enable crash reporting only if no other crash reporter runs in the app;
// initialize Datadog before Firebase Crashlytics. With it on, an app hang
// also carries its stack.
// To enable it: import DatadogCrashReporting, then call
// CrashReporting.enable() right after Datadog.initialize.
Datadog.initialize(
with: Datadog.Configuration(
clientToken: "YOUR_KEY_HERE",
env: "prod",
service: Bundle.main.bundleIdentifier ?? "app"
),
trackingConsent: .granted)
RUM.enable(with: RUM.Configuration(
applicationID: Bundle.main.bundleIdentifier ?? "app",
// Name your screens yourself — .trackRUMView(name:) on a SwiftUI view,
// startView/stopView in a UIKit controller. Both *views* predicates stay nil:
// a default one names views by type on top of your names, so every screen
// gets a second identity. Both *actions* predicates stay on — a tap is
// hit-tested by exactly one framework, so they never compete for it.
uiKitViewsPredicate: nil,
uiKitActionsPredicate: DefaultUIKitRUMActionsPredicate(),
swiftUIViewsPredicate: nil,
swiftUIActionsPredicate: DefaultSwiftUIRUMActionsPredicate(isLegacyDetectionEnabled: false),
urlSessionTracking: .init(firstPartyHostsTracing: .trace(hosts: ["your-api-host.com"])),
trackBackgroundEvents: true,
// A hang from 0.7 s on (where Flamio counts a freeze), an ANR the
// app lived through and a kill by the system come as their own kinds of error.
appHangThreshold: 0.7,
trackWatchdogTerminations: true,
customEndpoint: URL(string: "https://api.flamio.org/api/v1/mobile/rum"),
// Datadog's own diagnostics: Flamio reads none of them.
telemetrySampleRate: 0))
URLSessionInstrumentation.enable(with: .init(delegateClass: DatadogURLSessionDelegate.self))
SessionReplay.enable(with: SessionReplay.Configuration(
replaySampleRate: 100,
textAndInputPrivacyLevel: .maskSensitiveInputs,
imagePrivacyLevel: .maskNone,
touchPrivacyLevel: .show,
customEndpoint: URL(string: "https://api.flamio.org/api/v1/mobile/replay"),
// Without this every SwiftUI screen records as one grey placeholder.
featureFlags: [.swiftui: true]))
Datadog.setUserInfo(id: currentUser.id, name: currentUser.name, email: currentUser.email)Yours to fill in: your-api-host.com is your own backend host; currentUser is your signed-in user — drop the setUserInfo call if you don’t identify users.
The bundle id is read from your app.
Android
// In the app module's build.gradle.kts, pin every Datadog module to exactly
// 3.13.1: from 3.15.0 the SDK sends screen updates On-Live does not read yet.
// implementation("com.datadoghq:dd-sdk-android-rum:3.13.1")
// implementation("com.datadoghq:dd-sdk-android-session-replay:3.13.1")
// implementation("com.datadoghq:dd-sdk-android-session-replay-compose:3.13.1")
// implementation("com.datadoghq:dd-sdk-android-compose:3.13.1")
// implementation("com.datadoghq:dd-sdk-android-okhttp:3.13.1")
// A WebView's page is recorded by the Flamio web SDK as a web session of its
// own: add the web SDK to that page. The page must be served over https (or
// from localhost) — the web SDK needs a secure context and does not start on
// http. Do not enable Datadog WebView tracking.
Datadog.initialize(
this,
Configuration.Builder(clientToken = "YOUR_KEY_HERE", env = "prod", service = packageName).build(),
TrackingConsent.GRANTED
)
Rum.enable(RumConfiguration.Builder(applicationId = packageName)
.useCustomEndpoint("https://api.flamio.org/api/v1/mobile/rum")
.trackBackgroundEvents(true)
.trackUserInteractions()
// Without this every Compose tap is unnamed, so a Compose screen reports no
// dead, rage or error clicks — trackUserInteractions() alone does not cover it.
.enableComposeActionTracking()
// Keep this even in a Compose app: it is the only thing that names an XML
// Activity. Compose destinations name themselves through NavigationEffect
// in the nav graph, and Flamio folds the host Activity into them.
.useViewTrackingStrategy(ActivityViewTrackingStrategy(true))
// An ANR the app lived through comes as its own kind of error: on Android 11
// and later the SDK otherwise reports only the ANRs that ended the app.
.trackNonFatalAnrs(true)
// Datadog's own diagnostics: Flamio reads none of them.
.setTelemetrySampleRate(0f)
.build())
val client = OkHttpClient.Builder()
.addInterceptor(DatadogInterceptor.Builder(listOf("your-api-host.com")).build())
.eventListenerFactory(DatadogEventListener.Factory())
.build()
SessionReplay.enable(SessionReplayConfiguration.Builder(sampleRate = 100f)
.useCustomEndpoint("https://api.flamio.org/api/v1/mobile/replay")
.setTextAndInputPrivacy(TextAndInputPrivacy.MASK_SENSITIVE_INPUTS)
.setImagePrivacy(ImagePrivacy.MASK_NONE)
.setTouchPrivacy(TouchPrivacy.SHOW)
.addExtensionSupport(ComposeExtensionSupport())
.build())
Datadog.setUserInfo(id = currentUser.id, name = currentUser.name, email = currentUser.email)Yours to fill in: your-api-host.com is your own backend host; currentUser is your signed-in user — drop the setUserInfo call if you don’t identify users.
The package name is read from your app.
React Native
// Install all three packages at exactly 3.7.0, without a ^ in package.json:
// from 3.11.0 they send screen updates On-Live does not read yet.
// npm install --save-exact @datadog/mobile-react-native@3.7.0 @datadog/mobile-react-native-session-replay@3.7.0 @datadog/mobile-react-navigation@3.7.0
import {
DatadogProvider,
DatadogProviderConfiguration,
DdSdkReactNative,
RumConfiguration,
TrackingConsent,
} from '@datadog/mobile-react-native';
import { DdRumReactNavigationTracking } from '@datadog/mobile-react-navigation';
import {
ImagePrivacyLevel,
SessionReplay,
TextAndInputPrivacyLevel,
TouchPrivacyLevel,
} from '@datadog/mobile-react-native-session-replay';
import type { SessionReplayConfiguration } from '@datadog/mobile-react-native-session-replay';
import { Platform } from 'react-native';
// Paper and Fabric, iOS and Android. A minified Android release also needs
// -keep class com.facebook.react.fabric.** { *; } and
// -keep class com.facebook.jni.** { *; } in proguard-rules.pro.
// A WebView's page is recorded by the Flamio web SDK as a web session of its
// own: add the web SDK to that page. The page must be served over https (or
// from localhost) — the web SDK needs a secure context and does not start on
// http. Do not enable Datadog WebView tracking.
const datadogConfiguration = new DatadogProviderConfiguration(
'YOUR_KEY_HERE',
'prod',
TrackingConsent.GRANTED,
{
service: 'com.your.app',
rumConfiguration: new RumConfiguration('com.your.app', true, true, true, {
customEndpoint: 'https://api.flamio.org/api/v1/mobile/rum',
// Required: without it every tap is named "RCTView", the React element
// type, so no dead, rage or error click lands on any one control.
// Give every control its own testID: a tap takes the closest testID up
// the tree, so an untagged button inside a tagged screen is named after
// the screen. With no testID on it or above it, its accessibilityLabel
// names it.
actionNameAttribute: 'testID',
// Native crash reports on Android. On iOS:
// Enable crash reporting only if no other crash reporter runs in the app;
// initialize Datadog before Firebase Crashlytics. With it on, an app hang
// also carries its stack.
nativeCrashReportEnabled: Platform.OS === 'android',
trackBackgroundEvents: true,
sessionSampleRate: 100,
// A hang from 0.7 s on (where Flamio counts a freeze), an ANR the
// app lived through and a kill by the system come as their own kinds of error.
appHangThreshold: 0.7,
trackNonFatalAnrs: true,
trackWatchdogTerminations: true,
// Datadog's own diagnostics: Flamio reads none of them.
telemetrySampleRate: 0,
}),
},
);
const sessionReplayConfiguration: SessionReplayConfiguration = {
replaySampleRate: 100,
textAndInputPrivacyLevel: TextAndInputPrivacyLevel.MASK_SENSITIVE_INPUTS,
imagePrivacyLevel: ImagePrivacyLevel.MASK_NONE,
touchPrivacyLevel: TouchPrivacyLevel.SHOW,
customEndpoint: 'https://api.flamio.org/api/v1/mobile/replay',
};
// Your app's root; navigationRef is your NavigationContainer's ref.
<DatadogProvider
configuration={datadogConfiguration}
onInitialization={() => {
SessionReplay.enable(sessionReplayConfiguration);
}}>
<NavigationContainer
ref={navigationRef}
onReady={() => {
DdRumReactNavigationTracking.startTrackingViews(
navigationRef.current,
);
}}>
</NavigationContainer>
</DatadogProvider>
// Once the user signs in (after DatadogProvider has initialized):
DdSdkReactNative.setUserInfo({
id: currentUser.id,
name: currentUser.name,
email: currentUser.email,
});Yours to fill in: com.your.app is your app’s bundle id; currentUser is your signed-in user — drop the setUserInfo call if you don’t identify users.
Flutter
import 'package:datadog_flutter_plugin/datadog_flutter_plugin.dart';
import 'package:datadog_session_replay/datadog_session_replay.dart';
import 'package:datadog_tracking_http_client/datadog_tracking_http_client.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
// datadog_flutter_plugin 3.7.0 with datadog_session_replay 1.0.0-preview.16 and
// datadog_tracking_http_client 3.3.0. Pin all three exactly: Session Replay is
// a preview at this version and may change its API without a major bump.
// This Session Replay needs Flutter 3.38 or later: it says 3.27, but it does
// not compile on 3.35.
// A platform view records nothing at all in the app's replay (a native map,
// ad or WebView inside Flutter): the preview has no platform-view recorder.
// Wrap a map, an ad or a camera preview in SessionReplayPrivacy(hide: true,
// child: ...): it records as a "Hidden" box, and taps on it no longer count as
// taps on the screen under it (four quick taps on a map read as a rage click).
// Text records as it appears; only sensitive inputs are masked. Wrap a part that
// shows personal data (client names, phone numbers, a code typed into Pinput)
// in SessionReplayPrivacy(textAndInputPrivacyLevel:
// TextAndInputPrivacyLevel.maskAll, child: ...).
// A WebView's page is recorded by the Flamio web SDK as a web session of its
// own: add the web SDK to that page. The page must be served over https (or
// from localhost) — the web SDK needs a secure context and does not start on
// http. Do not enable Datadog WebView tracking.
DatadogConfiguration buildDatadogConfiguration() {
final configuration = DatadogConfiguration(
clientToken: 'YOUR_KEY_HERE',
env: 'prod',
// Required by the constructor; the two custom endpoints decide where data goes.
site: DatadogSite.us1,
service: 'com.your.app',
// Native crash reports on Android. On iOS:
// Enable crash reporting only if no other crash reporter runs in the app;
// initialize Datadog before Firebase Crashlytics. With it on, an app hang
// also carries its stack.
nativeCrashReportEnabled: defaultTargetPlatform == TargetPlatform.android,
rumConfiguration: DatadogRumConfiguration(
applicationId: 'com.your.app',
customEndpoint: 'https://api.flamio.org/api/v1/mobile/rum',
sessionSamplingRate: 100,
detectLongTasks: true,
trackBackgroundEvents: true,
// Flutter's own build and raster time of each screen's frames.
reportFlutterPerformance: true,
// A hang from 0.7 s on (where Flamio counts a freeze), an ANR the
// app lived through and a kill by the system come as their own kinds of error.
appHangThreshold: 0.7,
trackWatchdogTerminations: true,
trackNonFatalAnrs: true,
// Datadog's own diagnostics: Flamio reads none of them.
telemetrySampleRate: 0,
),
)..enableSessionReplay(
DatadogSessionReplayConfiguration(
replaySampleRate: 100,
textAndInputPrivacyLevel: TextAndInputPrivacyLevel.maskSensitiveInputs,
imagePrivacyLevel: ImagePrivacyLevel.maskNone,
touchPrivacyLevel: TouchPrivacyLevel.show,
customEndpoint: 'https://api.flamio.org/api/v1/mobile/replay',
// Without it an image larger than about 800×800 pixels records as a
// "Large Image" placeholder instead of the picture.
imageDownscaling: ImageDownscaling.enabled,
),
)
// A dart:io HttpClient call is a RUM resource only through this override, so
// without it your requests are not in the network channel at all. It tracks
// every URL the app opens; firstPartyHosts would only add tracing headers.
// dio, package:http and the GraphQL clients built on them go through it too.
// A gRPC call does not: add DatadogGrpcInterceptor(DatadogSdk.instance, channel)
// (package datadog_grpc_interceptor) to each gRPC client's interceptors.
// Read each response's body (e.g. response.transform(utf8.decoder).join()):
// a response ended with drain() never closes its RUM resource
// (https://github.com/DataDog/dd-sdk-flutter/issues/1299).
..enableHttpTracking();
return configuration;
}
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
// Set your other error handlers (Firebase Crashlytics, Sentry) here, before
// runApp: Datadog keeps them and passes every error on. Set inside the
// callback, they replace Datadog's and no Dart error reaches Flamio.
await DatadogSdk.runApp(
buildDatadogConfiguration(),
TrackingConsent.granted,
() async => runApp(const MyApp()),
);
}
// Names a screen view after its route. An unnamed dialog, bottom sheet or menu
// is part of the screen under it, so opening or closing one starts no view; a
// page pushed without a route name gets the fallback name below, which Flamio
// reads as "no name" and names the screen from what it shows.
const _unnamedScreenViewName = 'unnamed-screen';
bool _isUnnamedPopup(Route<dynamic>? route) => route is PopupRoute && route.settings.name == null;
RumViewInfo? _screenViewInfo(Route<dynamic> route) =>
defaultViewInfoExtractor(route) ?? (route is PopupRoute ? null : RumViewInfo(name: _unnamedScreenViewName));
class FlamioNavigationObserver extends RouteObserver<ModalRoute<dynamic>> {
FlamioNavigationObserver({required DatadogSdk datadogSdk})
: datadogObserver = DatadogNavigationObserver(datadogSdk: datadogSdk, viewInfoExtractor: _screenViewInfo);
final DatadogNavigationObserver datadogObserver;
final List<Route<dynamic>> _routes = [];
// The screen a route change lands on: the route itself, or the screen under the popups on top of it.
Route<dynamic>? _screenAtOrBelow(Route<dynamic>? route) {
if (route == null) return null;
final index = _routes.indexOf(route);
for (var i = index; i >= 0; i -= 1) {
if (!_isUnnamedPopup(_routes[i])) return _routes[i];
}
return _isUnnamedPopup(route) ? null : route;
}
@override
void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
if (!_isUnnamedPopup(route)) datadogObserver.didPush(route, _screenAtOrBelow(previousRoute));
_routes.add(route);
super.didPush(route, previousRoute);
}
@override
void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
_routes.remove(route);
if (!_isUnnamedPopup(route)) datadogObserver.didPop(route, _screenAtOrBelow(previousRoute));
super.didPop(route, previousRoute);
}
@override
void didReplace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) {
final index = oldRoute == null ? -1 : _routes.indexOf(oldRoute);
if (index >= 0 && newRoute != null) _routes[index] = newRoute;
if (!_isUnnamedPopup(newRoute) || !_isUnnamedPopup(oldRoute)) {
datadogObserver.didReplace(newRoute: _screenAtOrBelow(newRoute), oldRoute: _isUnnamedPopup(oldRoute) ? null : oldRoute);
}
super.didReplace(newRoute: newRoute, oldRoute: oldRoute);
}
@override
void didRemove(Route<dynamic> route, Route<dynamic>? previousRoute) {
_routes.remove(route);
super.didRemove(route, previousRoute);
}
}
// With go_router, use this observer INSTEAD of FlamioNavigationObserver (it needs
// import 'package:go_router/go_router.dart'). A page observer sees only a nested
// route's own segment and an unnamed ShellRoute page; the router knows the full
// route path (/catalog/item/:id), so it names each screen. Pass it as
// GoRouter(observers: [goRouterViews], routes: ...) and, once the router is
// built, call goRouterViews.attach(router).
class FlamioGoRouterViews extends NavigatorObserver with WidgetsBindingObserver {
FlamioGoRouterViews({required this.datadogSdk});
final DatadogSdk datadogSdk;
late final GoRouter router;
void attach(GoRouter router) {
this.router = router;
router.routerDelegate.addListener(_sync);
WidgetsBinding.instance.addObserver(this);
_sync();
}
final List<Route<dynamic>> _pageless = [];
String? _current;
bool _isScreenOutsideRouter(Route<dynamic> route) =>
route.settings is! Page<dynamic> && !(route is PopupRoute && route.settings.name == null);
String? _location() {
if (_pageless.isNotEmpty) return _pageless.last.settings.name ?? _unnamedScreenViewName;
if (router.routerDelegate.currentConfiguration.isEmpty) return null;
final state = router.state;
return state.fullPath ?? state.uri.path;
}
void _sync() {
final resumed = (WidgetsBinding.instance.lifecycleState ?? AppLifecycleState.resumed) == AppLifecycleState.resumed;
final next = resumed ? _location() : null;
if (next == _current) return;
final rum = datadogSdk.rum;
if (_current != null) rum?.stopView(_current!);
_current = next;
if (next != null) rum?.startView(next, next);
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) => _sync();
@override
void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
if (!_isScreenOutsideRouter(route)) return;
_pageless.add(route);
_sync();
}
@override
void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
if (_pageless.remove(route)) _sync();
}
@override
void didRemove(Route<dynamic> route, Route<dynamic>? previousRoute) {
if (_pageless.remove(route)) _sync();
}
@override
void didReplace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) {
final index = oldRoute == null ? -1 : _pageless.indexOf(oldRoute);
if (index < 0) return;
if (newRoute != null && _isScreenOutsideRouter(newRoute)) {
_pageless[index] = newRoute;
} else {
_pageless.removeAt(index);
}
_sync();
}
}
// In your root widget's State: only what SessionReplayCapture wraps is
// recorded, and it needs a stable GlobalKey.
final _captureKey = GlobalKey();
late final FlamioNavigationObserver _navigationObserver =
FlamioNavigationObserver(datadogSdk: DatadogSdk.instance);
@override
Widget build(BuildContext context) {
return SessionReplayCapture(
key: _captureKey,
rum: DatadogSdk.instance.rum!,
sessionReplay: DatadogSessionReplay.instance!,
child: MaterialApp(
navigatorObservers: [_navigationObserver],
),
);
}
// Around every tappable control. Without it a tap is named after its visible
// label, so two controls that share a caption share one identity — and
// Semantics(identifier:) is never read by the SDK.
RumUserActionAnnotation(
description: 'add_to_cart',
child: ElevatedButton(onPressed: addToCart, child: const Text('Add to cart')),
)
// Once the user signs in:
DatadogSdk.instance.setUserInfo(id: currentUser.id, name: currentUser.name, email: currentUser.email);Yours to fill in: com.your.app is your app’s bundle id; currentUser is your signed-in user — drop the setUserInfo call if you don’t identify users.
Kotlin Multiplatform
// dd-sdk-kotlin-multiplatform 1.8.0, plus dd-sdk-kotlin-multiplatform-ktor3 for the
// Ktor client and dd-sdk-android-session-replay-compose in androidMain.
// Android Compose and iOS SwiftUI/UIKit screens only —
// Compose Multiplatform UI is not supported: it records as one blank shape.
// The endpoint must be https: a Kotlin Multiplatform Android app cannot upload
// over clear-text http at all.
// A WebView's page is recorded by the Flamio web SDK as a web session of its
// own: add the web SDK to that page. The page must be served over https (or
// from localhost) — the web SDK needs a secure context and does not start on
// http. Do not enable Datadog WebView tracking.
// commonMain
import com.datadog.kmp.Datadog
import com.datadog.kmp.core.configuration.Configuration
import com.datadog.kmp.ktor.datadogKtorPlugin
import com.datadog.kmp.privacy.TrackingConsent
import com.datadog.kmp.rum.Rum
import com.datadog.kmp.rum.RumMonitor
import com.datadog.kmp.rum.configuration.RumConfiguration
import com.datadog.kmp.sessionreplay.SessionReplay
import com.datadog.kmp.sessionreplay.configuration.ImagePrivacy
import com.datadog.kmp.sessionreplay.configuration.SessionReplayConfiguration
import com.datadog.kmp.sessionreplay.configuration.TextAndInputPrivacy
import com.datadog.kmp.sessionreplay.configuration.TouchPrivacy
import io.ktor.client.HttpClient
internal expect fun applyPlatformRumTracking(builder: RumConfiguration.Builder): RumConfiguration.Builder
internal expect fun applyPlatformSessionReplay(
builder: SessionReplayConfiguration.Builder,
): SessionReplayConfiguration.Builder
Datadog.initialize(
platformContext,
Configuration.Builder(
clientToken = "YOUR_KEY_HERE",
env = "prod",
service = "com.your.app",
).build(),
TrackingConsent.GRANTED,
)
Rum.enable(
applyPlatformRumTracking(
RumConfiguration.Builder("com.your.app")
.useCustomEndpoint("https://api.flamio.org/api/v1/mobile/rum")
.trackBackgroundEvents(true)
// Datadog's own diagnostics: Flamio reads none of them.
.setTelemetrySampleRate(0f),
).build(),
)
SessionReplay.enable(
applyPlatformSessionReplay(
SessionReplayConfiguration.Builder(100f)
.useCustomEndpoint("https://api.flamio.org/api/v1/mobile/replay")
.setTextAndInputPrivacy(TextAndInputPrivacy.MASK_SENSITIVE_INPUTS)
.setImagePrivacy(ImagePrivacy.MASK_NONE)
.setTouchPrivacy(TouchPrivacy.SHOW),
).build(),
)
// Name every screen yourself: the multiplatform SDK bridges no view-tracking
// strategy on either OS, so without these two calls a session arrives with no
// pages at all. On Android call them as each screen appears and goes away — a
// Compose destination's LifecycleResumeEffect, a plain Activity's
// onResume/onPause. On iOS name SwiftUI screens with dd-sdk-ios's own
// .trackRUMView(name:) modifier on each screen's root view instead.
RumMonitor.get().startView("catalog", "catalog")
RumMonitor.get().stopView("catalog")
// Your API calls go through one Ktor client with the Datadog plugin. Without it
// no request is a RUM resource, so no error click fires on either OS.
val client = HttpClient { install(datadogKtorPlugin(tracedHosts = listOf("your-api-host.com"))) }
Datadog.setUserInfo(id = currentUser.id, name = currentUser.name, email = currentUser.email)
// androidMain
// The two platform calls are extension functions — and ComposeExtensionSupport
// comes from the Android SDK, not the multiplatform one.
import com.datadog.android.sessionreplay.compose.ComposeExtensionSupport
import com.datadog.kmp.rum.configuration.trackNonFatalAnrs
import com.datadog.kmp.rum.configuration.trackUserInteractions
import com.datadog.kmp.sessionreplay.configuration.addExtensionSupport
// An ANR the app lived through comes as its own kind of error.
internal actual fun applyPlatformRumTracking(
builder: RumConfiguration.Builder,
): RumConfiguration.Builder = builder.trackUserInteractions().trackNonFatalAnrs(true)
// Required: without it a Compose screen is not recorded at all.
internal actual fun applyPlatformSessionReplay(
builder: SessionReplayConfiguration.Builder,
): SessionReplayConfiguration.Builder = builder.addExtensionSupport(ComposeExtensionSupport())
// A Compose tap on Android exists only where your app calls
// RumMonitor.get().addAction(...): Kotlin Multiplatform has no bridge to
// Datadog's Compose action tracking, and a tap on a disabled control yields none.
// iosMain
import com.datadog.kmp.rum.configuration.setAppHangThreshold
import com.datadog.kmp.rum.configuration.trackUiKitActions
import com.datadog.kmp.rum.configuration.trackWatchdogTerminations
import com.datadog.kmp.sessionreplay.configuration.enableSwiftUISupport
// Required: a UIKit control cannot name its own tap otherwise. A SwiftUI tap is
// named by .trackRUMTapAction(name:) on the control — leave trackSwiftUIActions
// off, or the tap reports the class (SwiftUI_Button) instead of your name.
// A hang from 700 ms on and a kill by the system come as their own kinds of error.
internal actual fun applyPlatformRumTracking(
builder: RumConfiguration.Builder,
): RumConfiguration.Builder = builder.trackUiKitActions()
.setAppHangThreshold(700)
.trackWatchdogTerminations(true)
// Required: without it every SwiftUI screen records as one placeholder.
internal actual fun applyPlatformSessionReplay(
builder: SessionReplayConfiguration.Builder,
): SessionReplayConfiguration.Builder = builder.enableSwiftUISupport(true)Yours to fill in: your-api-host.com is your own backend host; com.your.app is your app’s bundle id; currentUser is your signed-in user — drop the setUserInfo call if you don’t identify users.
Also replace catalog with each screen's own name.
Related
- Watch a visit replay
- See how fast your app is
- Find and triage issues
- Project settings — add a mobile app to a project
- Troubleshooting