Skip to content

Commit cab4b4f

Browse files
committed
docs(android): Add Navigation 3 integration docs
Document Navigation 3 support on the Android navigation integration page and clarify how it differs from the existing Navigation 2 integration. Align the examples with the current SDK API shape, including route name extraction, optional argument extraction, back stack capture options, and route data scrubbing.
1 parent 3e5106a commit cab4b4f

5 files changed

Lines changed: 290 additions & 9 deletions

File tree

410 KB
Loading
174 KB
Loading
233 KB
Loading
213 KB
Loading

‎docs/platforms/android/integrations/navigation/index.mdx‎

Lines changed: 290 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,25 +3,43 @@ title: Navigation
33
caseStyle: camelCase
44
supportLevel: production
55
sdk: sentry.java.android.navigation
6-
description: "Learn more about the Sentry Navigation integration for the Android SDK."
6+
description: "Learn more about Sentry's navigation integrations for the Android SDK."
77
categories:
88
- mobile
99
---
1010

11-
The `sentry-android-navigation` library provides [AndroidX Navigation](https://developer.android.com/jetpack/androidx/releases/navigation) support for Sentry using the [SentryNavigationListener](https://github.com/getsentry/sentry-java/blob/524ee49b212c3f2eead20960c3c6825ccdbf8007/sentry-android-navigation/src/main/java/io/sentry/android/navigation/SentryNavigationListener.kt). The source can be found [on GitHub](https://github.com/getsentry/sentry-java/tree/main/sentry-android-navigation/src/main/java/io/sentry/android/navigation).
11+
The `sentry-android-navigation` and `sentry-android-navigation3` libraries provide support for Sentry's Android navigation instrumentation. Use them to automatically add breadcrumbs, track screen names, and start navigation transactions whenever users navigate around your app.
1212

13-
On this page, we get you up and running with Sentry's Navigation Integration, so that it will automatically add a breadcrumb and start a transaction for each navigation event.
13+
This page covers both:
1414

15-
## Install
15+
- **Navigation 2** (`androidx.navigation`) via `SentryNavigationListener`
16+
- **Navigation 3** (`androidx.navigation3`) via `SentryNavEffect`
17+
18+
If you're still using `NavController`, follow the Navigation 2 setup below. If you've moved to `NavDisplay`, skip to [Navigation 3](#navigation-3).
19+
20+
## Navigation 2
21+
22+
<Alert>
23+
24+
If you're using Navigation 2 with Jetpack Compose, see <PlatformLink to="/configuration/integrations/jetpack-compose/#jetpack-compose-navigation">Jetpack Compose Navigation</PlatformLink> instead.
25+
26+
</Alert>
27+
28+
### Install
1629

1730
Sentry captures data by adding a `NavController.OnDestinationChangedListener`. To add the Navigation integration, install the [Android SDK](/platforms/android/), then add the `sentry-android-navigation` dependency using Gradle:
1831

19-
```groovy
32+
```groovy {filename:build.gradle}
2033
implementation 'io.sentry:sentry-android:{{@inject packages.version('sentry.java.android', '6.2.0') }}'
2134
implementation 'io.sentry:sentry-android-navigation:{{@inject packages.version('sentry.java.android.navigation', '6.2.0') }}'
2235
```
2336

24-
## Configure
37+
```kotlin {filename:build.gradle.kts}
38+
implementation("io.sentry:sentry-android:{{@inject packages.version('sentry.java.android', '6.2.0') }}")
39+
implementation("io.sentry:sentry-android-navigation:{{@inject packages.version('sentry.java.android.navigation', '6.2.0') }}")
40+
```
41+
42+
### Configure
2543

2644
Configuration should happen in the respective lifecycle callbacks, once you retrieve your `NavController` instance:
2745

@@ -72,9 +90,9 @@ protected void onPause() {
7290

7391
By default, the navigation transaction finishes automatically after it reaches the specified [idleTimeout](/platforms/android/configuration/options/#idleTimeout) and all of its child spans are finished. You can customize the timeout to your needs.
7492

75-
## Verify
93+
### Verify
7694

77-
This snippet includes a sample `Fragment` with a couple of navigation events and captures an intentional message, so you can test that everything is working as soon as you set it up:
95+
The snippet below includes a sample `Fragment` with a couple of navigation events and captures an intentional message, so you can test that everything is working as soon as you set it up:
7896

7997
```kotlin
8098
import android.os.Bundle
@@ -121,7 +139,7 @@ class HomeFragment : Fragment() {
121139
}
122140
```
123141

124-
## Customize the Recorded Breadcrumb/Transaction
142+
### Customize the Recorded Breadcrumb/Transaction
125143

126144
By default, the Navigation integration captures route arguments as additional data on breadcrumbs and transactions. In case the arguments contain any PII data, you can strip it out by way of `BeforeBreadcrumbCallback` and `EventProcessor` respectively. To do that, [manually initialize](/platforms/android/manual-setup/#configuration-via-sentryoptions) the SDK and add the following snippet:
127145

@@ -149,3 +167,266 @@ SentryAndroid.init(this) { options ->
149167
})
150168
}
151169
```
170+
171+
## Navigation 3
172+
173+
<Alert>
174+
175+
Navigation 3 support is available in `sentry-android-navigation3` `8.60.0` and later.
176+
177+
See the [Limitations](#limitations) section below for additional restrictions.
178+
179+
</Alert>
180+
181+
Android's [Navigation 3 library](https://developer.android.com/guide/navigation/navigation-3) expects apps to manage their own back stack and to push and pop entries in order to navigate. Apps pass their back stack to a `NavDisplay` and define corresponding composables. `NavDisplay` renders those composables to screen as the back stack entries change.
182+
183+
`SentryNavEffect` instruments the back stack passed to `NavDisplay`. By default, every time the top of the back stack changes, `SentryNavEffect` will:
184+
185+
- start a new navigation transaction (and finish any prior navigation transaction)
186+
- emit a breadcrumb
187+
- update the currently tracked screen name
188+
- record the latest 10 entries from the back stack as event context
189+
190+
See [Customize Nav3 Options](#customize-nav3-options) to learn how to modify those defaults.
191+
192+
### Install
193+
194+
Install the Android SDK and add Sentry's Navigation 3 library:
195+
196+
```groovy {filename:build.gradle}
197+
dependencies {
198+
implementation 'io.sentry:sentry-android:{{@inject packages.version('sentry.java.android', '8.60.0') }}'
199+
implementation 'io.sentry:sentry-android-navigation3:{{@inject packages.version('sentry.java.android.navigation', '8.60.0') }}'
200+
}
201+
```
202+
203+
```kotlin {filename:build.gradle.kts}
204+
dependencies {
205+
implementation("io.sentry:sentry-android:{{@inject packages.version('sentry.java.android', '8.60.0') }}")
206+
implementation("io.sentry:sentry-android-navigation3:{{@inject packages.version('sentry.java.android.navigation', '8.60.0') }}")
207+
}
208+
```
209+
210+
### Configure
211+
212+
To use `SentryNavEffect`, add it to the composable that owns your `NavDisplay` and pass your back stack to both:
213+
214+
```kotlin
215+
import androidx.navigation3.runtime.NavKey
216+
import androidx.navigation3.runtime.rememberNavBackStack
217+
import androidx.navigation3.ui.NavDisplay
218+
import io.sentry.compose.navigation3.SentryNavEffect
219+
import kotlinx.serialization.Serializable
220+
221+
@Composable
222+
fun AppNavigation() {
223+
// Create your back stack like usual.
224+
val backStack = rememberNavBackStack(Route.Home)
225+
226+
// Place SentryNavEffect in the same composable as your NavDisplay and call the
227+
// effect first. Provide a BackStackEntryMapper with the values you want to
228+
// show up in Sentry. Be sure to omit PII and other sensitive info.
229+
SentryNavEffect(
230+
backStack = backStack,
231+
backStackEntryMapper = { entry ->
232+
when (entry) {
233+
is Home -> SentryBackStackEntry("Home")
234+
is ProductDetail ->
235+
SentryBackStackEntry("ProductDetail", mapOf("product_id" to entry.productId))
236+
...
237+
}
238+
}
239+
)
240+
241+
// Configure your NavDisplay like usual.
242+
NavDisplay(
243+
backStack = backStack,
244+
...
245+
)
246+
}
247+
```
248+
249+
**Note:** Be sure to call `SentryNavEffect` before `NavDisplay` so the effect's transaction-creating machinery can be set up before any spans are produced by the initial nav destination. Otherwise, initial destination spans may be lost or parented under the wrong transaction.
250+
251+
Provide a `BackStackEntryMapper` that maps each entry in your back stack to the name and optional arguments you want displayed in Sentry. Keep names stable and arguments lightweight and performant. Avoid using `::class.simpleName` or anything else that R8 will obfuscate.
252+
253+
<Alert>
254+
255+
Values returned from `BackStackEntryMapper` are **not** scrubbed by the Sentry SDK of PII or other potentially sensitive information before being sent to Sentry. Only return names and arguments known to be safe, or sanitize them yourself in your `BackStackEntryMapper`.
256+
257+
</Alert>
258+
259+
260+
<Alert>
261+
262+
Multiple, simultaneously active `SentryNavEffect` instances writing to the same [Sentry scope](https://docs.sentry.io/platforms/android/enriching-events/scopes/) are ***not*** supported. Violating this restriction can result in duplicated or interleaved data and undefined transaction behavior.
263+
264+
</Alert>
265+
266+
### Customize Nav3 Options
267+
268+
Use `SentryNavOptions` to disable breadcrumbs or transactions, or to limit how much of the back stack Sentry stores with captured events.
269+
270+
```kotlin
271+
import io.sentry.compose.navigation3.SentryNavEffect
272+
import io.sentry.compose.navigation3.SentryNavOptions
273+
274+
SentryNavEffect(
275+
backStack = backStack,
276+
...
277+
options = SentryNavOptions {
278+
enableNavigationBreadcrumbs = true
279+
enableNavigationTransactions = true
280+
captureBackStack = true
281+
maxCapturedBackStackEntries = 5
282+
},
283+
)
284+
```
285+
286+
If you want to turn screen names on or off, configure the main SDK options when you initialize the Sentry SDK:
287+
288+
```kotlin
289+
import io.sentry.android.core.SentryAndroid
290+
291+
SentryAndroid.init(this) { options ->
292+
options.isEnableScreenTracking = true
293+
}
294+
```
295+
296+
### Verify
297+
298+
The snippet below defines `Home` and `ProductDetail` routes and a composable for displaying them. It adds both routes to an in-memory back stack and captures a message from the `ProductDetail` destination so you can verify the navigation data the Sentry SDK emits.
299+
300+
The snippet assumes the default `SentryNavOptions`. Screen names additionally require screen tracking to be enabled.
301+
302+
```kotlin
303+
import androidx.compose.material3.Button
304+
import androidx.compose.material3.Text
305+
import androidx.compose.runtime.Composable
306+
import androidx.compose.runtime.LaunchedEffect
307+
import androidx.compose.runtime.mutableStateListOf
308+
import androidx.compose.runtime.remember
309+
import androidx.navigation3.runtime.NavKey
310+
import androidx.navigation3.runtime.entryProvider
311+
import androidx.navigation3.ui.NavDisplay
312+
import io.sentry.Sentry
313+
import io.sentry.compose.navigation3.SentryBackStackEntry
314+
import io.sentry.compose.navigation3.SentryNavEffect
315+
import kotlinx.coroutines.delay
316+
317+
data object Home : NavKey
318+
319+
data class ProductDetail(val productId: String) : NavKey
320+
321+
@Composable
322+
fun AppNavigation() {
323+
val backStack = remember { mutableStateListOf<NavKey>(Home) }
324+
325+
SentryNavEffect(
326+
backStack = backStack,
327+
backStackEntryMapper = { entry ->
328+
when (entry) {
329+
is Home -> SentryBackStackEntry("Home")
330+
is ProductDetail -> SentryBackStackEntry(
331+
name = "ProductDetail",
332+
arguments = mapOf("product_id" to entry.productId),
333+
)
334+
else -> null
335+
}
336+
},
337+
)
338+
339+
NavDisplay(
340+
backStack = backStack,
341+
onBack = { backStack.removeLastOrNull() },
342+
entryProvider = entryProvider {
343+
entry<Home> {
344+
Button(
345+
onClick = {
346+
backStack.add(ProductDetail(productId = "nav3-smoke-test"))
347+
},
348+
) {
349+
Text("Open product detail")
350+
}
351+
}
352+
entry<ProductDetail> {
353+
val parentSpan = Sentry.getSpan()
354+
355+
// Generate a fake span so that the nav transaction isn't dropped after its idle timeout
356+
// expires.
357+
LaunchedEffect(parentSpan) {
358+
val span =
359+
parentSpan?.startChild(
360+
"test.navigation.product_detail",
361+
"ProductDetail work",
362+
)
363+
try {
364+
delay(100)
365+
} finally {
366+
span?.finish()
367+
}
368+
}
369+
370+
Button(onClick = { Sentry.captureMessage("Navigation 3 smoke test") }) {
371+
Text("Send test message")
372+
}
373+
}
374+
},
375+
)
376+
}
377+
```
378+
379+
Tap **Open product detail**, then **Send test message**. In Sentry, open the event for `Navigation 3 smoke test` and verify the following:
380+
381+
- In **Breadcrumbs**, look for a navigation breadcrumb whose destination is `ProductDetail`. It should include `product_id` under `to_arguments`.
382+
383+
![Navigation breadcrumb from Home to ProductDetail with the product_id argument](./img/breadcrumb.png)
384+
385+
- In **Contexts**, check the Navigation context for a back stack containing `/ProductDetail` followed by `/Home`, with `product_id` under `entry_arguments`. Also check the App context for View Names containing `/ProductDetail`.
386+
387+
![Navigation context showing ProductDetail and Home in the back stack, with the product_id argument](./img/back-stack-context.png)
388+
![App context showing ProductDetail under View Names](./img/screen-name.png)
389+
390+
- If tracing is enabled and the transaction is sampled, open the [Traces](https://sentry.io/orgredirect/organizations/:orgslug/traces/) view after the [idle timeout](/platforms/android/configuration/options/#idleTimeout) and inspect the `ProductDetail` transaction. Emitted nav data should appear under **Attributes → Arguments**, **Contexts → Navigation**, and **Breadcrumbs**.
391+
392+
![ProductDetail navigation transaction with its child span and product_id argument](./img/nav-transaction.png)
393+
394+
### Using kotlinx.serialization
395+
396+
If your Nav3 back stack uses `@Serializable` keys, you can use [Kotlin serialization](https://kotlinlang.org/docs/serialization.html) to produce stable entry names. For performance reasons, don't serialize keys in their entirety as `arguments` if they might be large, deeply nested, or contain PII or other sensitive information.
397+
398+
```kotlin
399+
import androidx.navigation3.runtime.NavKey
400+
import io.sentry.compose.navigation3.BackStackEntryMapper
401+
import io.sentry.compose.navigation3.SentryBackStackEntry
402+
import kotlinx.serialization.SerialName
403+
import kotlinx.serialization.Serializable
404+
405+
@Serializable
406+
@SerialName("Home")
407+
data class Home(userName: String) : NavKey
408+
409+
@Serializable
410+
@SerialName("ProductDetail")
411+
data class ProductDetail(userName: String, productId: String) : NavKey
412+
413+
val backStackItemMapper = BackStackEntryMapper<NavKey> { entry ->
414+
when (entry) {
415+
is Home -> SentryBackStackEntry(Home.serializer().descriptor.serialName)
416+
is ProductDetail -> SentryBackStackEntry(
417+
name = ProductDetail.serializer().descriptor.serialName,
418+
arguments = mapOf("product_id" to entry.productId)
419+
)
420+
...
421+
}
422+
}
423+
```
424+
425+
### Limitations
426+
427+
`SentryNavEffect` treats the top entry in your back stack as the current screen. That works well for most Nav3 setups, but it means that `SentryNavEffect` does ***not***:
428+
429+
- understand the concept of Nav3 [Scenes](https://developer.android.com/guide/navigation/navigation-3/scenes) or multi-pane layouts
430+
- track multiple back stacks
431+
- permit multiple, simultaneously active `SentryNavEffect` instances
432+
- make special accommodations for [predictive back](https://developer.android.com/guide/navigation/custom-back/predictive-back-gesture) gestures (e.g., spans produced by predictively rendered composables may appear under the current destination's transaction)

0 commit comments

Comments
 (0)