Tracker

  • Tracker is used to compose and send hits to Google Analytics and must be initialized with a tracking ID.

  • Values set using theset method are sent with all subsequent hits until overwritten or cleared, while values in asend call are sent only with that specific hit.

  • Trackers can be configured programmatically or via an XML resource file in the app's res/xml/ directory.

  • Key configuration options include tracking ID, sampling rate, auto activity tracking, IP anonymization, uncaught exception reporting, and session timeout.

  • When auto activity tracking is enabled, you can specify alternate screen names for activities in the XML configuration.

public classTracker extendsObject

Composes and sends hits to Google Analytics. You can get an instance of this class by callingGoogleAnalytics.newTracker(int). A Tracker must be initialized with a tracking id of an app profile before you can send any hits. Use this class to set values for measurement protocol parameters using the provided set methods. A param value set using set(String, String) method is sent with all subsequent hits until you overwrite it with another value or clear it by setting it tonull. You can also override it by specifying a different value in a send(Map) call. The values passed in the send(Map) are sent only with that hit. The following example uses theHitBuilders.EventBuilder helper class to build a param map to pass to the send(Map) method.

 GoogleAnalytics analytics = GoogleAnalytics.getInstance(context); Tracker tracker = analytics.newTracker("UA-000-1"); // Send hits to tracker id UA-000-1 // All subsequent hits will be send with screen name = "main screen" tracker.setScreenName("main screen"); tracker.send(new HitBuilders.EventBuilder()         .setCategory("UX")         .setAction("click")         .setLabel("submit")         .build()); // Builder parameters can overwrite the screen name set on the tracker tracker.send(new HitBuilders.EventBuilder()         .setCategory("UX")         .setAction("click")         .setLabel("help popup")         .setScreenName("help popup dialog")         .build());
ATracker can also beinitialized with configuration values from an XML resource file like this:
 Tracker tracker = analytics.newTracker(R.xml.tracker_config);
Where R.xml.tracker_config isthe resource id for an XML configuration file. The file should be stored in the app's res/xml/directory and look like this:
 <?xml version="1.0" encoding="utf-8" ?> <resources>     <string name="ga_trackingId">UA-0000-1</string>     <string name="ga_sampleFrequency">100.0</string>     <integer name="ga_sessionTimeout">1800</integer>     <bool name="ga_autoActivityTracking">true</bool>     <bool name="ga_anonymizeIp">false</bool>     <bool name="ga_reportUncaughtExceptions">true</bool>     <screenName name="com.example.MainActivity">Home Screen</screenName>     <screenName name="com.example.SecondActivity">Second Screen</screenName> </resources>
The following tracker configuration values can be specified:
  • ga_trackingId(string) - tracking id to send the reports to. Required.
  • ga_sampleFrequency(string) - sampling rate in percents. Default is 100.0. It can be any value between 0.0 and 100.0.
  • ga_autoActivityTracking(bool) - if true, views (Activities) will be tracked. Default is false.
  • ga_anonymizeIp(bool) - if true, anonymizeIp will be set for each hit. Default is false.
  • ga_reportUncaughtExceptions(bool) - if true, uncaught exceptions will be tracked. Default is false. NOTE: This value can only be set to true for a single Tracker. If specified for multiple Trackers, then the last one to be initialized will be used.
  • ga_sessionTimeout(int) - time (in seconds) an app can stay in the background before a new session is started. Setting this to a negative number will result in a new session never being started. Default is 1800 seconds (30 minutes).

If ga_autoActivityTracking is enabled, an alternate screen name can be specified to substitute for the full canonicalActivity class name. In order to specify an alternate screen name use an <screenName> element, with the name attribute specifying the full class name, and the screen name as element content.

 <screenName name="com.example.MainActivity">Home Screen</screenName>

Public Method Summary

void
enableAdvertisingIdCollection(boolean enabled)
Sets whether the advertising id and ad targeting preference should be collected while sending hits to GA servers.
void
enableAutoActivityTracking(boolean enabled)
Specify whetherActivity starts should automatically generate screen views from thisTracker.
void
enableExceptionReporting(boolean enable)
Enables or disables uncaught exception reporting for a given tracker.
String
get(String key)
Gets the model value for the given key.
void
send(Map<StringString> params)
Merges the model values set on this Tracker via send(Map) withparams and generates a hit to be sent.
void
set(String key,String value)
Sets the model value for the given key.
void
setAnonymizeIp(boolean anonymize)
void
setAppId(String appId)
Sets the id of the App for analytics reports.
void
setAppInstallerId(String appInstallerId)
Sets the Installer Id of the App for analytics reports.
void
setAppName(String appName)
Sets the name of the App for analytics reports.
void
setAppVersion(String appVersion)
Sets the version identifier of the App for analytics reports.
void
setCampaignParamsOnNextHit(Uri uri)
Includes the campaign parameters contained in the URI referrer in the next hit.
void
setClientId(String clientId)
Sets a particular client Id for the device.
void
void
void
setLanguage(String language)
Sets the language based on user's preferred locale.
void
void
void
void
setSampleRate(double sampleRate)
Set the sample rate for all hits generated by the app.
void
setScreenColors(String screenColors)
void
setScreenName(String screenName)
Set the screen name to be associated with all subsequent hits.
void
setScreenResolution(int width, int height)
Sets the screen resolution of the device.
void
setSessionTimeout(long sessionTimeout)
Specify the time (in seconds) an app can stay in the background before a new session is started.
void
void
setUseSecure(boolean useSecure)
Sets whether hits should be sent securely over https.
void
setViewportSize(String viewportSize)

Inherited Method Summary

From class java.lang.Object
Object
clone()
boolean
equals(Object arg0)
void
finalize()
finalClass<?>
getClass()
int
hashCode()
final void
notify()
final void
notifyAll()
String
toString()
final void
wait(long arg0, int arg1)
final void
wait(long arg0)
final void
wait()

Public Methods

public voidenableAdvertisingIdCollection(boolean enabled)

Sets whether the advertising id and ad targeting preference should be collected while sending hits to GA servers. The collection of advertising id and the ad targeting preference is disabled by default and needs to be turned on for mobile audience features and any other features that require advertising id.

Parameters
enabledtrue if the advertising information should be collected. False otherwise.

public voidenableAutoActivityTracking(boolean enabled)

Specify whetherActivity starts should automatically generate screen views from thisTracker.

Parameters
enabledTrue if screen views should be automatically generated.

public voidenableExceptionReporting(boolean enable)

Enables or disables uncaught exception reporting for a given tracker. This method is equivalent to using 'ga_reportUncaughtExceptions' in the tracker configuration file. Note that as with the configuration setting, only the uncaught exceptions are reported using this method.

publicStringget(String key)

Gets the model value for the given key. Returns null if no model value has been set.

public voidsend(Map<StringString> params)

Merges the model values set on this Tracker via send(Map) withparams and generates a hit to be sent. The hit may not be dispatched immediately. Note that the hit type must set for the hit to be considered valid. More information on this can be found at //goo.gl/HVIXHR.

Parameters
paramsmap of hit data to values which are merged with the existing values which are already set (using set(String, String)). Values in this map will override the values set earlier. The values in this map will not be reused for the subsequent hits. If you need to send a value in multiple hits, you can use the set(String, String) method.

public voidset(String key,String value)

Sets the model value for the given key. All subsequent track or send calls will send this key-value pair along as well. To remove a particular field, simply set the value to null.

Parameters
keyThe key of the field that needs to be set. It starts with "&" followed by the parameter name. The complete list of fields can be found at //goo.gl/M6dK2U.
valueA string value to be sent to Google servers. A null value denotes that the value should not be sent over wire.

public voidsetAnonymizeIp(boolean anonymize)

public voidsetAppId(String appId)

Sets the id of the App for analytics reports. This value is populated by default using the information provided by the android package manager. This value is usually the package name used by the app.

Parameters
appIdString representing the name of the app.

public voidsetAppInstallerId(String appInstallerId)

Sets the Installer Id of the App for analytics reports. This value is populated by default using the information provided by the android package manager and the play store.

Parameters
appInstallerIdString representing the name of the app.

public voidsetAppName(String appName)

Sets the name of the App for analytics reports. This value is populated by default using the information provided by the android package manager.

Parameters
appNameString representing the name of the app.

public voidsetAppVersion(String appVersion)

Sets the version identifier of the App for analytics reports. This value is populated by default using the information provided by the android package manager.

Parameters
appVersionString representing the version of the app.

public voidsetCampaignParamsOnNextHit(Uri uri)

Includes the campaign parameters contained in the URI referrer in the next hit. If there is no referrer, or the referrer does not contain campaign parameters, this method does not add anything to the next hit.

Use this method to track in-app events driven by advertising with deep linking campaigns.

Valid campaign parameters are:

  • utm_id
  • utm_campaign
  • utm_content
  • utm_medium
  • utm_source
  • utm_term
  • dclid
  • gclid

Example: //my.site.com/index.html?referrer=utm_source%3Dsource%26utm_campaign%3Dwow

Parameters
urithe uri containing the referrer

public voidsetClientId(String clientId)

Sets a particular client Id for the device. This Id should be a valid UUID (version 4) string as described in //goo.gl/0dlrGx. If not specified, the SDK automatically generates one for you and sets it.

Parameters
clientIdA valid version 4 UUID string.

public voidsetEncoding(String encoding)

public voidsetHostname(String hostname)

public voidsetLanguage(String language)

Sets the language based on user's preferred locale. The string should be of the format ll-cc where ll is the language and cc is the country. If no value is provided, the default value from the android SDK is used.

Parameters
languagestring that denotes a particular language/locale.

public voidsetLocation(String location)

public voidsetPage(String page)

public voidsetReferrer(String referrer)

public voidsetSampleRate(double sampleRate)

Set the sample rate for all hits generated by the app. The sampling is done at app level. The default value is 100. To enable sampling, the minimum rate required is 0.01%.

Parameters
sampleRateA value between 0 and 100, specifying the percentage of devices that should send hits.

public voidsetScreenColors(String screenColors)

public voidsetScreenName(String screenName)

Set the screen name to be associated with all subsequent hits.

Parameters
screenNamethe name of the screen, ornull to clear its value.

public voidsetScreenResolution(int width, int height)

Sets the screen resolution of the device. If no resolution is specified, the default resolution from the android SDK is used.

Parameters
widthinteger representing the width in pixels.
heightinteger representing the height in pixels.

public voidsetSessionTimeout(long sessionTimeout)

Specify the time (in seconds) an app can stay in the background before a new session is started. Setting this to a negative number will result in a new session never being started. Default is 30 seconds.

Parameters
sessionTimeoutSession timeout time in seconds.

public voidsetTitle(String title)

public voidsetUseSecure(boolean useSecure)

Sets whether hits should be sent securely over https. The default value is true.

public voidsetViewportSize(String viewportSize)

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2024-10-31 UTC.