Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I track Fragments in Google Analytics v4?

With the release of Google Analytics v4 (Android), what is the recommended way to track Fragment views? Is this solution still the recommended way - https://stackoverflow.com/a/19284014/413254?

The sample in the docs (https://developers.google.com/analytics/devguides/collection/android/v4/#analytics-xml) has the following config:

global_tracker.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <integer name="ga_sessionTimeout">300</integer>
    <bool name="ga_autoActivityTracking">true</bool>
    <screenName name="com.google.android.gms.analytics.samples.mobileplayground.ScreenviewFragment">
        AnalyticsSampleApp ScreenView
    </screenName>
    <screenName name="com.google.android.gms.analytics.samples.mobileplayground.EcommerceFragment">
        AnalyticsSampleApp EcommerceView
    </screenName>
    <!--  The following value should be replaced with correct property id. -->
    <string name="ga_trackingId">UA-XXXXXXX-Y</string>
</resources>

This configuration looks to be enabling auto tracking for Activities, but I'd assume this doesn't work any magic for Fragments? In this example, I'd assume the "AnalyticsSampleApp ScreenView" screen event will be sent if t.setScreenName(path); is called and path is "com.google.android.gms.analytics.samples.mobileplayground.EcommerceFragment"?

like image 426
loeschg Avatar asked Apr 02 '14 19:04

loeschg


1 Answers

Yes, you'll have to use the solution described in the link you posted. The main reason for this is because the lifetime of fragments is not as straightforward as that of Activities. Android does not provide callbacks for fragment lifecycle.

What you should do is set the fragment identifier as the screen name whenever the fragment is shown. In the sample app, if you look at MobilePlayground.java, you'll see onTabSelected. In the sample app, this function is called whenever the screen changes. That would be a good place to set screen and possibly send screenview/appview hits.

Let me know if you want more detailed examples.

like image 143
Avi Avatar answered Sep 24 '22 17:09

Avi