2

In the previous XML-based Android development, it was relatively straightforward to track screen views in Google Analytics by using separate activities for each screen.

Now that I’m using Jetpack Compose with a single-activity architecture and Navigation Compose, I'm not sure what the best approach is to track screen views.

How can I properly track screen views in Jetpack Compose using Google Analytics (e.g., Firebase Analytics)?

Are there any recommended best practices or patterns for this in a Compose + Navigation setup?

Should I track the screens manually using NavBackStackEntry, or is there a better built-in way?

I’m looking for a clean and scalable solution that works well with modern Compose apps. Any advice, code snippets, or official recommendations would be really helpful.

1 Answer 1

2

If you just want to track the screen Name, the easiest way to put the tracking code in app level with NavHost, so whenever route change it will push the changes.

@Composable
fun ScreenTracking(
    navController: NavHostController,
    analytics: FirebaseAnalytics
) {
    val navBackStackEntry by navController.currentBackStackEntryAsState()
    val currentDestination = navBackStackEntry?.destination

    LaunchedEffect(currentDestination) {
        currentDestination?.route?.let { route ->
            analytics.logEvent(FirebaseAnalytics.Event.SCREEN_VIEW) {
                param(FirebaseAnalytics.Param.SCREEN_NAME, route)
            }
        }
    }
}

Then, use it like this:-

@Composable
fun MyApp(firebaseAnalytics: FirebaseAnalytics) {
    val navController = rememberNavController()

    Scaffold {
        ScreenTracking(navController, firebaseAnalytics)

        NavHost(navController = navController, startDestination = "home") {
            composable("home") { HomeScreen() }
            composable("profile") { ProfileScreen() }
            // ...
        }
    }
}

Optional:- You can also use only the prefix or your own custom logic get the screen name

fun cleanScreenName(route: String): String {
    return route.substringBefore("/") // or use your custom logic
}

Second Approach:
Recommended way by NIA(Now in android) official google repo worth to have a look into that, scalable replaceable if any other libs easily. and you can also add some extra params if want, but in this case in each screen you have to manually put the tracking code.

NIA Analytics Sample by Google

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.