Jetpack Navigation and Firebase Analytics

Firebase Analytics is the default choice for mobile app analytics these days. With a very few steps, the Firebase Analytics SDK for Android and iOS can be integrated within minutes. By default, Firebase Analytics track your screens without any additional code implementations.

However, it is designed to only automatically track screen views or screen visits when you are launching new Activities. If you are using Fragments, Firebase Analytics will not report any new screen views when you are navigating between fragments within the same Activity. Moreover, with the Single Activity design and Jetpack Navigation approach, which is now being recommended by the Android team at Google, the standard integration will not automatically record and report your screen views. It will only report the launch or visit of your Activity or Activities.

So, how do you now report your screen views to Firebase Analytics?

You have to add a few lines of code. Just a few.

Step 1

To your NavigationController, attach the onDestinationChangedListener. It has a single method with the following definition. Here, I have created a function which needs to be called from your single activity.

private fun setupScreenTracking() {        navController.addOnDestinationChangedListener { _, destination, _ ->
...
}
}

Step 2

Create a reference to FirebaseAnalytics in your single activity, which will be needed later.

class HomeActivity : AppCompatActivity() {
...
private lateinit var firebaseAnalytics: FirebaseAnalytics
...
override fun onCreate(savedInstanceState: Bundle?) {
....
firebaseAnalytics = FirebaseAnalytics.getInstance(this)
....

Step 3

Report screen views as events to FirebaseAnalytics through the reference that you have just created.

private fun setupScreenTracking() {
navController.addOnDestinationChangedListener { _, destination, _ ->
var
params = Bundle()
params.putString(FirebaseAnalytics.Param.SCREEN_NAME, destination.label as String?)
params.putString(FirebaseAnalytics.Param.SCREEN_CLASS, destination.label as String?)
firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SCREEN_VIEW, params)
}
}

That’s it. Now you are all set. Just about 7 lines of code. Now, whenever you changes destinations, your screen views will be automatically reported. For the sake of this example, I am using the Fragment’s label as the screen name. This should work in most of the scenarios. However, you can have your own logic of generating the screen names.

While my phone and the laptop is being charged, I love to write, cook and ride away from the city on my bicycle.