Advanced Configuration - Android SDK

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

Overview

The Google Analytics SDK 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 GoogleAnalytics singleton by providing a Context and a Google Analytics property ID:

// Initialize a tracker using a Google Analytics property ID.
GoogleAnalytics.getInstance(this).getTracker("UA-XXXX-Y")

Now this tracker can be used for setting and sending data to Google Analytics.

Setting and Sending Data

Data is sent to Google Analytics by setting maps of parameter-value pairs on the tracker and sending them via the set and send methods:

/*
 * Send a screen view to Google Analytics by setting a map of parameter
 * values on the tracker and calling send.
 */
Tracker tracker = GoogleAnalytics.getInstance(this).getTracker("UA-XXXX-Y");

HashMap<String, String> hitParameters = new HashMap<String, String>();
hitParameters.put(Fields.HIT_TYPE, "appview");
hitParameters.put(Fields.SCREEN_NAME, "Home Screen");

tracker.send(hitParameters);

The MapBuilder class simplifies the process of building hits and is recommended for most use cases. Here we can send the same screen view with fewer lines of code:

// Sending the same screen view hit using MapBuilder.createAppView()
tracker.send(MapBuilder
  .createAppView()
  .set(Fields.SCREEN_NAME, "Home Screen")
  .build()
);

Measurement Protocol Ampersand Syntax

Values may also be set on a single hit, by setting the value on a Builder, or on all subsequent hits, by setting it on the tracker object itself, using the Measurement Protocol ampersand syntax:

// Setting the content description field on a single hit using ampersand syntax.
tracker.send(MapBuilder
  .createAppView()
  .set(Fields.SCREEN_NAME, "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:

// Set screen name on the tracker to be sent with all hits.
tracker.set(Fields.SCREEN_NAME, "Home Screen");

// Send a screen view for "Home Screen"
tracker.send(MapBuilder
    .createAppView()
    .build()
);

// This event will also be sent with &cd=Home%20Screen.
tracker.send(MapBuilder
    .createEvent("UX", "touch", "menuButton", null)
    .build()
);

// Clear the screen name field when we're done.
tracker.set(Fields.SCREEN_NAME, 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

Multiple trackers may be used in a single implementation, which can be useful for sending data to multiple properties:

Tracker t1 = GoogleAnalytics.getInstance(this).getTracker("UA-XXXX-1");

// Trackers may be named. By default, name is set to the property ID.
Tracker t2 = GoogleAnalytics.getInstance(this).getTracker("altTracker", "UA-XXXX-2";

t1.set(Fields.SCREEN_NAME, "Home Screen");
t2.set(Fields.SCREEN_NAME, getClass().toString());

// Send screen view to UA-XXXX-1.
t1.send(MapBuilder
   .createAppView()
   .build()
);

// Send screen view to UA-XXXX-2.
t2.send(MapBuilder
   .createAppView()
   .build()
);

Automated measurement features, like automatic screen and uncaught exception measurement, will only use one tracker to send data to Google Analytics. If you are using these features and want to send data using other trackers, you will need to do so manually.

Using the Default Tracker

Google Analytics maintains a default tracker. The first tracker initialized becomes the default tracker but may be overridden:

// Tracker t1 becomes the default tracker because it is initialized first.
Tracker t1 = GoogleAnalytics.getInstance(this).getTracker("UA-XXXX-1");
Tracker t2 = GoogleAnalytics.getInstance(this).getTracker("UA-XXXX-2");


// Returns tracker t1.
Tracker defaultTracker = GoogleAnalytics.getInstance(this).getDefaultTracker();

// Hit sent to UA-XXXX-1.
defaultTracker.send(MapBuilder
    .createAppView()
    .set(Fields.SCREEN_NAME, "Home Screen")
    .build()
);

// Override the default tracker.
GoogleAnalytics.getInstance(this).setDefaultTracker(t2);

// Now this call returns tracker t2.
defaultTracker = GoogleAnalytics.getInstance(this).getDefaultTracker();

// Hit sent to UA-XXXX-2.
defaultTracker.send(MapBuilder
    .createAppView()
    .set(Fields.SCREEN_NAME, getClass().toString())
    .build()
);

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% via EasyTracker and XML, use the following parameter in your analytics.xml file:

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

To enable client-side sampling programmatically for a tracker:

mTracker.set(Fields.SAMPLE_RATE, 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 NO.

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.
    }
  }
});

Testing and Debugging

The Google Analytics SDK 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

The Logger interface is provided to handle useful messages from the SDK at these levels of verbosity: error, warning, info, and verbose.

The SDK initializes a standard Logger implementation, which by default will only log warning or error messages to console. These messages will be available in logcat. To set the verbosity of the Logger:

// Set the log level to verbose.
GoogleAnalytics.getInstance(this).getLogger()
    .setLogLevel(LogLevel.VERBOSE);

Custom implementations of Logger can also be used:

// Provide a custom logger.
GoogleAnalytics.getInstance(this).setLogger(new CustomLogger ());

Complete Example

The example below shows the code required to initialize a Google Analytics implementation and send a single screen view.

package com.example.app;

import com.google.analytics.tracking.android.GAServiceManager;
import com.google.analytics.tracking.android.GoogleAnalytics;
import com.google.analytics.tracking.android.Tracker;

import android.app.Application;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;


/*
 * An advanced Google Analytics implementation may be initialized
 * in a subclass of Application. Note that this example assumes data
 * only needs to be sent to a single Google Analytics property ID.
 */
public class MyApp extends Application {

  private static GoogleAnalytics mGa;
  private static Tracker mTracker;

  /*
   * Google Analytics configuration values.
   */
  // Placeholder property ID.
  private static final String GA_PROPERTY_ID = "UA-XXXX-Y";

  // Dispatch period in seconds.
  private static final int GA_DISPATCH_PERIOD = 30;

  // Prevent hits from being sent to reports, i.e. during testing.
  private static final boolean GA_IS_DRY_RUN = false;

  // GA Logger verbosity.
  private static final LogLevel GA_LOG_VERBOSITY = LogLevel.INFO;

  // Key used to store a user's tracking preferences in SharedPreferences.
  private static final String TRACKING_PREF_KEY = "trackingPreference";


  /*
   * Method to handle basic Google Analytics initialization. This call will not
   * block as all Google Analytics work occurs off the main thread.
   */
  private void initializeGa() {
    mGa = GoogleAnalytics.getInstance(this);
    mTracker = mGa.getTracker(GA_PROPERTY_ID);

    // Set dispatch period.
    GAServiceManager.getInstance().setLocalDispatchPeriod(GA_DISPATCH_PERIOD);

    // Set dryRun flag.
    mGa.setDryRun(GA_IS_DRY_RUN);

    // Set Logger verbosity.
    mGa.getLogger().setLogLevel(GA_LOG_VERBOSITY);

    // Set the opt out flag when user updates a tracking preference.
    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));
        }
      }
    });
  }

  @Override
  public void onCreate() {
    super.onCreate();
    initializeGa();
  }

  /*
   * Returns the Google Analytics tracker.
   */
  public static Tracker getGaTracker() {
    return mTracker;
  }

  /*
   * Returns the Google Analytics instance.
   */
  public static GoogleAnalytics getGaInstance() {
    return mGa;
  }
}

Next, a screen view is measured when the first screen is displayed to a user:

package com.example.app

import android.app.Activity

/**
 * A simple Activity that sends a screen view to Google Analytics
 * when it is displayed to the user.
 */
public class HomeScreen extends Activity {

  private static final String SCREEN_LABEL = "Home Screen";

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Fields set on a tracker persist for all hits, until they are
    // overridden or cleared by assignment to null.
    MyApp.getGaTracker().set(Fields.SCREEN_NAME, SCREEN_LABEL);
  }

  @Override
  public void onStart() {
    super.onStart();

    // Send a screen view when the Activity is displayed to the user.
    MyApp.getGaTracker().send(MapBuilder
        .createAppView.build());
  }
}