Google Analytics SDK for Android v1 (Legacy)

The Google Analytics for Mobile Apps SDK for Android makes it easy to implement Google Analytics in an Android-based applications. This document describes how to integrate the SDK with your apps.

SDK Overview

This SDK uses a tracking model that is designed to track users to traditional websites and interaction with widgets in traditional web pages. For this reason, the terms used below reflect the conventional website tracking model and are being mapped over to tracking mobile applications. You should be familiar with Analytics tracking in order to understand how this SDK works.

Use the mobile tracking SDK to track your phone applications with the following Analytics interaction types:

Pageview Tracking
A pageview is a standard means to measure traffic volume to a traditional website. Because mobile apps don't contain HTML pages, you must decide when (and how often) to trigger a pageview request. Also, since pageview requests are designed to report on directory structures, you should provide descriptive names for the requests to take advantage of page path naming in the Content reports in Analytics. The names you choose will be populated in your Analytics reports as page paths even though they are not actually HTML pages, but you can use this to your advantage by structuring paths to provide additional groupings for your calls.
Event Tracking
In Analytics, events are designed to track user interaction to web page elements distinctly from pageview requests. You can use the Event Tracking feature of Google Analytics to make additional calls that will be reported in the Event Tracking section of the Analytics report interface. Events are grouped using categories and may also use per-event labels, which provides flexibility in reporting. For example, a multimedia app could have play/stop/pause actions for its video category and assign a label for each video name. The Google Analytics reports would then aggregate events for all events tagged with the video category. For more information on Event Tracking, see the Event Tracking Guide
Ecommerce Tracking
Use the Ecommerce tracking feature to track shopping cart transactions and in-app purchases. To track a transaction, use the Transaction class to represent the overall purchase information as well as the Item class to represent each product in the shopping basket. Once collected, the data can then be viewed in the Ecommerce reporting section of the Google Analytics interface. For more information on Ecommerce Tracking, see the Ecommerce Tracking Guide.
Custom Variables
Custom variables are name-value pair tags that you can insert in your tracking code in order to refine Google Analytics tracking. For more information on how you can use custom variables, read the Custom Variable Guide.

Getting Started


To integrate Google Analytics' tracking capabilities with your Android app, you will need the following:


  • Add libGoogleAnalytics.jar to your project's /libs directory.
  • Add the following permissions to your project's AndroidManifest.xml manifest file:
    • <uses-permission android:name="android.permission.INTERNET" />
    • <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

An example application is included with the SDK that demonstrates what your project should look like if set up successfully. Feel free to use it as a template for your own Analytics-integrated apps.

Using the SDK

Before you begin using the SDK, you must first create a free account at and create a new web property in that account using a fake but descriptive website URL (e.g. Once you create the property, write down or keep a copy of the web property ID that is generated for the newly-created property.

You must indicate to your users, either in the application itself or in your terms of service, that you reserve the right to anonymously track and report a user's activity inside of your app. Your use of the Google Analytics SDK is additionally governed by the Google Analytics Terms of Service, which you must agree to when signing up for an account.

Samples and Best Practices

You can find sample code and best practices at under the project analytics-api-samples.

EasyTracker Library

An EasyTracker Library is available. It provides application and Activity level tracking with almost no development effort. You can find it in the Downloads section of the analytics-api-samples project.

Starting the Tracker

Obtain the tracker singleton by calling GoogleAnalyticsTracker.getInstance(). Then call its startNewSession method, passing the web property ID and activity being tracked. You may call this method directly in the onCreate method of your Activity if your application has only one Activity. For example:



import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class TestActivity extends Activity {

  GoogleAnalyticsTracker tracker;

  protected void onCreate(Bundle savedInstanceState) {

    tracker = GoogleAnalyticsTracker.getInstance();

    // Start the tracker in manual dispatch mode...
    tracker.startNewSession("UA-YOUR-ACCOUNT-HERE", this);

    // ...alternatively, the tracker can be started with a dispatch interval (in seconds).
    //tracker.startNewSession("UA-YOUR-ACCOUNT-HERE", 20, this);

    Button createEventButton = (Button)findViewById(;
    createEventButton.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
            "Clicks",  // Category
            "Button",  // Action
            "clicked", // Label
            77);       // Value

    Button createPageButton = (Button)findViewById(;
    createPageButton.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        // Add a Custom Variable to this pageview, with name of "Medium" and value "MobileApp" and
        // scope of session-level.
        tracker.setCustomVar(1, "Navigation Type", "Button click", 2);
        // Track a page view. This is probably the best way to track which parts of your application
        // are being used.
        // E.g.
        // tracker.trackPageView("/help"); to track someone looking at the help screen.
        // tracker.trackPageView("/level2"); to track someone reaching level 2 in a game.
        // tracker.trackPageView("/uploadScreen"); to track someone using an upload screen.

    Button quitButton = (Button)findViewById(;
    quitButton.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {

    Button dispatchButton = (Button)findViewById(;
    dispatchButton.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        // Manually start a dispatch, not needed if the tracker was started with a dispatch
        // interval.

  protected void onDestroy() {
    // Stop the tracker when it is no longer needed.

If you have multiple Activities in your application, you can use the EasyTracker Library provided in the Downloads section of the analytics-api-samples project.

Tracking Pageviews and Events

Tracking pageviews and events is straightforward: simply call trackPageView of the tracker object each time you wish to trigger a pageview. Call trackEvent to record an event. For more on pageviews and events, see SDK Overview above.

Using Custom Variables

Adding a custom variable is also straightforward: just use the setCustomVar method provided by the mobile SDK. You'll want to plan out ahead of time which indexes each custom variable maps to, so you don't overwrite any previously existing variable. For more information on custom variables, see the Custom Variable Guide. Note that the method setCustomVar does not directly send data on its own. Rather the data is sent with the next tracked pageview or event. You have to call setCustomVar before you track a pageview or event. Note that the default scope of Custom Variables is page scoped.

Using Ecommerce Tracking

There are 4 methods you use to enable Ecommerce tracking in your application:

  • addTransaction
  • addItem
  • trackTransactions
  • clearTransactions

Calling addTransaction and addItem adds the transaction or item to an internal Ecommerce buffer, to which more items and transactions can be added. Only when calling trackTransactions will the transactions and items be sent to the dispatcher and get queued to be sent to Google Analytics.

To clear the buffer, you can call the clearTransactions method. Note: it does not recall any transactions previously sent to the dispatcher nor any transactions already collected by Google Analytics.

The following sample code can get you started. We assume that the method onPurchaseCompleted is called when the purchase is confirmed or denied.

   * The purchase was processed.  We will track the transaction and its associated line items
   * now, but only if the purchase has been confirmed.
   * @param purchase A PurchaseObject containing all of the transaction information needed to
   *     send the ecommerce hit to Google Analytics.
  public void onPurchaseCompleted(PurchaseObject purchase) {
    tracker.addTransaction(new Transaction.Builder(
    for (PurchaseLineItem lineItem : purchase.getLineItems()) {
        tracker.addItem(new Item.Builder(
    if (purchase.isConfirmed()) {
    } else {
      // The purchase was denied or failed in some way.  We need to clear out
      // any data we've already put in the Ecommerce buffer.

For more information on Ecommerce, see Ecommerce Tracking Guide.

Anonymize IP

To anonymize user IP information, use the setAnonymizeIp method. This tells Google Analytics to anonymize the information sent by the SDK by removing the last octet of the IP address prior to its storage.

You can call setAnonymizeIp at any time.

Setting Sample Rate

You can set the sample rate using the method setSampleRate. If your application generates a lot of Analytics traffic, setting the sample rate may prevent your reports from being generated using sampled data. Sampling occurs consistently across unique users, so there is integrity in trending and reporting when sample rate is enabled. The setSampleRate method accepts one int parameter. Valid values for that parameter are any integer between 0 and 100, inclusive.

A rate of 0 turns off hit generation, while a rate of 100 sends all data to Google Analytics. It's best to call setSampleRate prior to calling any tracking methods.

You can learn more about sampling from the Sampling Concepts Guide.

Batching Hits

To save on connection and battery overhead, we recommend batching your tracking requests. You can call dispatch on the tracking object any time you want to make a batch request, and you can do this either manually or at specific time intervals.

Known Issues

  • Calling GoogleAnalyticsTracker methods on different threads can result in obscure errors. Be sure to make all your calls from the same thread.
  • Tracking Campaigns

    The SDK supports two types of campaign tracking.

    - Google Play Campaign Tracking – Allows you to track installation referrals through Google Play.
    - General Campaign Tracking – Allows you to track any campaign that refers users to your application.

    Google Play Campaign Tracking

    The Android 1.6 OS release supports the use of a referrer URL parameter in download links to Google Play. The Google Analytics SDK for Android uses this parameter to automatically populate campaign information in Google Analytics for your application. This enables the source of the application install to be recorded and associated with future pageviews and events, which can be useful for gauging the effectiveness of a particular advertisement for your app for example.

    In order for referral tracking to work, you must add the following code snippet to your project's AndroidManifest.xml manifest file:

    <!-- Used for install referrer tracking -->
    <receiver android:name="" android:exported="true">
        <action android:name="" />

    To set up Google Analytics campaign tracking through Google Play, use the URL builder below to generate a referral link. Use the link to refer users to your application. The Analytics SDK will automatically parse and record the referral information and populate it in your Analytics report.

    To generate the referral link, you can use the Google Play Campaign URL Builder. Package Name, Campaign Source, Campaign Medium, and Campaign Name are required. For a detailed description of each parameter, see the table below.

    General Campaign Tracking

    With version 1.3 of the Google Analytics SDK for Android, you can now track campaigns for sources other than Google Play. For example, if you wish to know that your application was launched from a link in an ad, you can check for campaign referral information in the intent that caused your application to be launched, then store that campaign information in Google Analytics.

    To set the campaign referral information, use the setReferrer method like so:


    There are two restrictions to using this feature. First, you must call startNewSession prior to calling setReferrer. You need to do this because the SQLite database used by Google Analytics isn’t set up prior to calling startNewSession and setReferrer needs that database. If you haven’t called startNewSession, you’ll get an IllegalStateException.

    The second restriction is that the referral string passed into setReferrer needs to follow a specific format. It must take the form of a set of URL parameters and must include at least a gclid parameter or one each of utm_campaign, utm_medium and utm_source. In the latter case, it can have utm_term and utm_content parameters as well.

    The gclid parameter is part of the autotagging feature that automatically links Google Analytics to Google Ads. A sample campaign referral using autotagging might look like:

    referrer = “gclid=gclidValue”;

    The manual campaign referral string might look like:

    referrer = “utm_campaign=campaign&utm_source=source&utm_medium=medium&utm_term=term&utm_content=content”;

    If you pass in a badly formed referrer string to setReferrer, the referrer information will not be changed and you’ll get a return value of false. A return value of true indicates that the referrer was updated and will be added to every hit going forward.

    Also note that a new session will be started when you call setReferrer and it returns true.

    Parameter Required Description Example(s)
    utm_campaign Yes Campaign name; used for keyword analysis to identify a specific product promotion or strategic campaign utm_campaign=spring_sale
    utm_source Yes Campaign source; used to identify a search engine, newsletter, or other source utm_source=google
    utm_medium Yes Campaign medium; used to identify a medium such as email or cost-per-click (cpc) utm_medium=cpc
    utm_term No Campaign term; used with paid search to supply the keywords for ads utm_term=running+shoes
    utm_content No Campaign content; used for A/B testing and content-targeted ads to differentiate ads or links that point to the same URL utm_content=logolink