How to track android fragments using firebase analytics

Zhen Liu picture Zhen Liu · Jul 19, 2017 · Viewed 17.6k times · Source

In my android application, I have an Activity that has 3 or 4 fragments that can be attached in sequence based on some user or server events.

I would like to track all these fragments as screens in firebase.

So ideally, if possible, is there an API i can invoke in the onCreate of the fragments, and tell firebase that user is currently in fragment1, fragment2 or fragment3?

Answer

Artem Mostyaev picture Artem Mostyaev · Jul 20, 2017

UPDATE

Since the setCurrentScreen is deprecated, you can use logEvent method

Bundle bundle = new Bundle();
bundle.putString(FirebaseAnalytics.Param.SCREEN_NAME, fragment.getClass().getSimpleName());
bundle.putString(FirebaseAnalytics.Param.SCREEN_CLASS, fragment.getClass().getSimpleName());
mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.SCREEN_VIEW, bundle);

I've used the following adb commands to check if all is working fine.

adb shell setprop log.tag.FA VERBOSE
adb shell setprop log.tag.FA-SVC VERBOSE
adb logcat -v time -s FA FA-SVC

Once you do that you'll see screen_view events in the logcat. Like this one:

10-15 13:14:13.744 V/FA-SVC (20323): Logging event: origin=app,name=screen_view(_vs),params=Bundle[{ga_event_origin(_o)=app, engagement_time_msec(_et)=31600, ga_previous_class(_pc)=ContentsFragment, ga_previous_id(_pi)=8077407744361472421, ga_previous_screen(_pn)=ContentsFragment, ga_screen_class(_sc)=TestFragment, ga_screen_id(_si)=8077407744361472423, ga_screen(_sn)=TestFragment}]

Previous answer

There is a special method to set a current screen - setCurrentScreen

I used it as follows

mFirebaseAnalytics.setCurrentScreen(this, fragment.getClass().getSimpleName(), fragment.getClass().getSimpleName());

Once the method is called, the following message appears in the LogCat

Logging event (FE): screen_view(_vs), Bundle[{firebase_event_origin(_o)=auto, firebase_previous_class(_pc)=HomeFragment, firebase_previous_id(_pi)=4121566113087629222, firebase_previous_screen(_pn)=HomeFragment, firebase_screen_class(_sc)=StatisticsFragment, firebase_screen_id(_si)=4121566113087629223, firebase_screen(_sn)=StatisticsFragment}]

The following event appears on auto activity tracking:

Logging event (FE): screen_view(_vs), Bundle[{firebase_event_origin(_o)=auto, firebase_previous_class(_pc)=StatisticsFragment, firebase_previous_id(_pi)=4121566113087629223, firebase_previous_screen(_pn)=StatisticsFragment, firebase_screen_class(_sc)=LoginActivity, firebase_screen_id(_si)=4121566113087629224}]

As you see, they are almost the same, so setCurrentScreen is working.

I'm able to see those classes in Firebase Console only on the next day. It is normal for Firebase - it takes time to process such amounts of data.

Firebase Console