Advanced Configuration

This document provides an overview of some of the advanced configuration features of the Google Analytics SDK v4 for Android.

Overview

The Google Analytics SDK v4 for Android provides a Tracker class to set and send data to Google Analytics, and a GoogleAnalytics singleton that serves as an interface to the global configuration values of your implementation.

Initialization

Before any data can be measured, you must initialize at least one tracker via the GoogleAnalytics singleton by providing a Context object and a Google Analytics property ID. For details, see the GoogleAnalytics Reference.

Using a Configuration File

It is also possible to initialize a tracker using a configuration file. For example:

package com.google.android.apps.mobileplayground;

import android.app.Application;
import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.Tracker;
import java.util.HashMap;

/**
 * An extension to Application class to provide tracker for analytics purposes. Having the tracker
 * instances here allows all the activities to access the same tracker instances. The trackers can
 * be initialised on startup or when they are required based on performance requirements.
 */
public class AnalyticsSampleApp extends Application {

  // The following line should be changed to include the correct property id.
  private static final String PROPERTY_ID = "UA-XXXXX-Y";

  /**
   * Enum used to identify the tracker that needs to be used for tracking.
   *
   * A single tracker is usually enough for most purposes. In case you do need multiple trackers,
   * storing them all in Application object helps ensure that they are created only once per
   * application instance.
   */
  public enum TrackerName {
    APP_TRACKER, // Tracker used only in this app.
    GLOBAL_TRACKER, // Tracker used by all the apps from a company. eg: roll-up tracking.
    ECOMMERCE_TRACKER, // Tracker used by all ecommerce transactions from a company.
  }

  HashMap<TrackerName, Tracker> mTrackers = new HashMap<TrackerName, Tracker>();

  public AnalyticsSampleApp() {
    super();
  }
  synchronized Tracker getTracker(TrackerName trackerId) {
    if (!mTrackers.containsKey(trackerId)) {

      GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
      Tracker t = (trackerId == TrackerName.APP_TRACKER) ? analytics.newTracker(PROPERTY_ID)
          : (trackerId == TrackerName.GLOBAL_TRACKER) ? analytics.newTracker(R.xml.global_tracker)
              : analytics.newTracker(R.xml.ecommerce_tracker);
      mTrackers.put(trackerId, t);

    }
    return mTrackers.get(trackerId);
  }
}

Setting and Sending Data

Data is sent to Google Analytics using builders to set parameter-value pairs sending them via the tracker send method.

The following example shows how to send a screen view to Google Analytics by building an app view and calling the tracker send method:

// Get tracker.
Tracker t = ((AnalyticsSampleApp) getActivity().getApplication()).getTracker(
    TrackerName.APP_TRACKER);

// Set screen name.
t.setScreenName(screenName);

// Send a screen view.
t.send(new HitBuilders.ScreenViewBuilder().build());

Measurement Protocol Ampersand Syntax

You can use the Measurement Protocol ampersand syntax to set values on a single hit with a HitBuilders.ScreenViewBuilder. To set values on all subsequent hits, use the tracker object itself.

// Setting the content description field on a single hit using ampersand syntax.
tracker.send(new HitBuilders.ScreenViewBuilder()
  .set("&cd", "Home Screen")
  .build()
);

For the complete list of available measurement protocol parameters, see the Measurement Protocol Parameter Reference.

Applying Values to Multiple Hits

Any values set on the tracker directly will be persisted and applied to multiple hits, as in this example:

// Get tracker.
Tracker t = ((AnalyticsSampleApp) getActivity().getApplication()).getTracker(
    TrackerName.APP_TRACKER);

// Set screen name.
t.setScreenName(screenName);

// Send a screen view.
t.send(new HitBuilders.ScreenViewBuilder().build());

// This event will also be sent with the most recently set screen name.
// Build and send an Event.
t.send(new HitBuilders.EventBuilder()
    .setCategory(getString(categoryId))
    .setAction(getString(actionId))
    .setLabel(getString(labelId))
    .build());

// Clear the screen name field when we're done.
t.setScreenName(null);

Only values that you want to persist across multiple hits should be set directly on the tracker. Setting a screen name on a tracker would make sense, since the same value can be applied to subsequent screen view and event hits. However, it is not recommended to set a field like hit type on the tracker, because it will likely change with each hit.

Using Multiple Trackers

In your mobile application, you can use multiple trackers to send data to different properties:


public class MyApp extends Application {

  public void initTrackers() {
    GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);

    globalTracker = analytics.newTracker(R.xml.global_tracker);
    ecommerceTracker = analytics.newTracker(R.xml.ecommerce_tracker);
  }

  public static Tracker globalTracker;
  public static Tracker ecommerceTracker;

  ...
}

Although your mobile application can have multiple trackers, you can use only one tracker to report uncaught exceptions by calling the enableExceptionReporting() method on the tracker.

Sampling

You can enable client-side sampling to limit the number of hits sent to Google Analytics. If your app has a large number of users or otherwise sends a large volume of data to Google Analytics, enabling sampling will help ensure un-interrupted reporting.

For example, to enable client-side sampling at a rate of 50%, use the following parameter in your configuration file:

<string name="ga_sampleFrequency">50.0</string>

To enable client-side sampling programmatically for a tracker:

mTracker.setSampleRate(50.0d);

App-level Opt Out

You can enable an app-level opt out flag that will disable Google Analytics across the entire app. Note that this flag must be set each time the app starts up and will default to false.

To get the app-level opt out setting, use:

boolean isOptedOut = GoogleAnalytics.getInstance(this).getAppOptOut();

To set the app-level opt out, use:

GoogleAnalytics.getInstance(this).setAppOptOut(true);

In a typical implementation, an app might listen for a change in SharedPreferences, and update the Google Analytics opt out setting accordingly:

SharedPreferences userPrefs = PreferenceManager.getDefaultSharedPreferences(this);

userPrefs.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener () {

  @Override
  public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    if (key.equals(TRACKING_PREF_KEY)) {
      GoogleAnalytics.getInstance(getApplicationContext()).setAppOptOut(sharedPreferences.getBoolean(key, false));
    } else {
      // Any additional changed preference handling.
    }
  }
});

Delete client-side user data

If you need to reset or delete Google Analytics client-side data for your end users you can delete the Client Id file.

Deleting the gaClientId file will force the generation of a new Client Id and all subsequent hits will use the new Client Id. Prior data will not be associated with the new Client Id.

To delete the gaClientId file use the Context.deleteFile method:

context.deleteFile("gaClientId");

Anonymize IP

Enabling anonymize IP functionality tells Google Analytics to anonymize the IP information sent by the SDK by removing the last octet of the IP address prior to its storage.

To enable anonymize IP functionality, use the following parameter in your configuration file:

<string name="ga_anonymizeIp">true</string>

To enable anonymize IP functionality programmatically for a tracker use the setAnonymizeIp method:

mTracker.setAnonymizeIp(true)

The setAnonymizeIp method can be called at any time.

Testing and Debugging

The Google Analytics SDK v4 for Android provides tools to make testing and debugging easier.

Dry Run

The SDK provides a dryRun flag that when set, prevents any data from being sent to Google Analytics. The dryRun flag should be set whenever you are testing or debugging an implementation and do not want test data to appear in your Google Analytics reports.

To set the dry run flag:

// When dry run is set, hits will not be dispatched, but will still be logged as
// though they were dispatched.
GoogleAnalytics.getInstance(this).setDryRun(true);

Logger

Google Analytics will log to logcat under the GAv4 tag using the Android Log system. By default only ERROR, WARN and INFO levels are enabled. To enable DEBUG level run the following adb command on your device or emulator:

adb shell setprop log.tag.GAv4 DEBUG

To see only Google Analytics messages from logcat use the following command:

adb logcat -v time -s GAv4

For more information, see the GoogleAnalytics Logger Reference.