Search code examples
androidgoogle-analyticsgoogle-analytics-firebase

How to set tracking ID after tracker created in Google Analytics v4 for Android?


In the Google Analytics SDK v4 for Android, the documentation says that you can create a tracker without initializing it with a tracking ID first:

If the trackingId is empty, you can still get a tracker, but you must set the tracking id before sending any hits. This is useful if you do not know the tracking id at the time of tracker creation, or if you want to use the same tracker instance to track multiple tracking ids.

  • The class overview of Tracker says:

A Tracker must be initialized with a tracking id of an app profile before you can send any hits. You can change the id to send hits to a different profile.

What method do you call to set the tracking ID after the tracker has been created?

Motivation

In the v3 version of the Android SDK, the configuration files could be split up, and I could use resource merging to define common values such as the tracking ID in src/main/res/values/analytics.xml and include debug attributes such as ga_dryRun in src/debug/res/values/analytics.xml.

But the v4 SDK now reads the configuration from res/xml which doesn't support resource merging AFAICT. I would like to define the tracking ID in one place, either Java or in XML, but also have the flexibility of different configuration files for different build variants.


Solution

  • Currently it is not possible to set the trakcing id after the tracker has been created. A HACKY way to do it is to use the Tracker.set() method with key = "&tid" and value as the tracking id.

    Thanks for describing your motivation though. We'll keep that in mind for future releases.

    CAUTION: The reason tracking id can only be set during creation is because tracker objects contain a lot of state data. It is highly recommended that the tracking id be not changed after the initial creation.

    PS: The hacky method will be supported for the foreseeable future but if you decide to use it, please confirm that the data can be seen in realtime reports before publishing the app.