Google Analytics

Advanced Configuration - Android SDK v4

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

  1. Overview
  2. Initialization
  3. Setting and Sending Data
    1. Using Multiple Trackers
  1. Sampling
  2. App-level Opt Out
  3. Testing and Debugging

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).newTracker("UA-XXXX-Y")

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

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 com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.Tracker;

import android.app.Application;

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.
        // Where path is a String representing the screen name.
        t.setScreenName(path);

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

Applying Values to Multiple Hits

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

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

        // Set screen name.
        // Where path is a String representing the screen name.
        t.setScreenName(path);

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

        // This event will also be sent with &cd=Home%20Screen.
        // 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

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

  // 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>();

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

Automated measurement for uncaught exceptions, 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.

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

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.
GoogeAnalytics.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 ());

Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.