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.
The Google Analytics for Mobile Apps SDKs provide an interface for tracking activity within mobile apps and reporting that activity to Google Analytics. For example you can use this SDK to calculate visits, session length, bounce rate and unique visitors. Tracking mobile applications has some structural variations from tracking website pages.
This SDK uses a tracking model that is designed to track visitors 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:
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.
To integrate Google Analytics' tracking capabilities with your Android app, you will need the following:
libGoogleAnalytics.jar to your project's /libs directory.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.
Before you begin using the SDK, you must first create a free account at www.google.com/analytics and create a new web property in that account using a fake but descriptive website URL (e.g. http://mymobileapp.mywebsite.com). Once you create the property, write down or keep a copy of the web property ID that is generated for the newly-created property.
A Web property ID is also known as the UA number of your tracking code and looks like UA-xxxxx-yy, where the x's and y's indicate the unique numbers for your profile. You must indicate the web property ID you'd like to use when instantiating the tracking object. See Web Property for more information.
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.
You can find sample code and best practices at code.google.com under the project analytics-api-samples.
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.
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:
package com.google.android.apps.analytics.sample;
import com.google.android.apps.analytics.GoogleAnalyticsTracker;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class TestActivity extends Activity {
GoogleAnalyticsTracker tracker;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(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);
setContentView(R.layout.main);
Button createEventButton = (Button)findViewById(R.id.NewEventButton);
createEventButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
tracker.trackEvent(
"Clicks", // Category
"Button", // Action
"clicked", // Label
77); // Value
}
});
Button createPageButton = (Button)findViewById(R.id.NewPageButton);
createPageButton.setOnClickListener(new OnClickListener() {
@Override
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.
tracker.trackPageView("/testApplicationHomeScreen");
}
});
Button quitButton = (Button)findViewById(R.id.QuitButton);
quitButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
Button dispatchButton = (Button)findViewById(R.id.DispatchButton);
dispatchButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Manually start a dispatch, not needed if the tracker was started with a dispatch
// interval.
tracker.dispatch();
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
// Stop the tracker when it is no longer needed.
tracker.stopSession();
}
}
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 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.
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.
There are 4 methods you use to enable Ecommerce tracking in your application:
addTransactionaddItemtrackTransactionsclearTransactionsCalling 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(
purchase.getOrderId(),
purchase.getTotal())
.setStoreName(purchase.getStoreName())
.setTotalTax(purchase.getTotalTax())
.setShippingCost(purchase.getShippingCost())
.build());
for (PurchaseLineItem lineItem : purchase.getLineItems()) {
tracker.addItem(new Item.Builder(
purchase.getOrderId(),
lineItem.getItemSKU(),
lineItem.getItemCost(),
lineItem.getQuantity())
.setItemName(lineItem.getItemName())
.setItemCategory(lineItem.getItemCategory())
.build());
}
if (purchase.isConfirmed()) {
tracker.trackTransactions();
} 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.
tracker.clearTransactions();
}
}
For more information on Ecommerce, see Ecommerce Tracking Guide.
To anonymize visitor 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.
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 visitors, 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.
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.
Tip: Bundle your tracker dispatches with other HTTP requests made by your application to reduce overhead.
The SDK supports two types of campaign tracking.
- Android Market Campaign Tracking – Allows you to track installation referrals through the Android Market.
- General Campaign Tracking – Allows you to track any campaign that refers users to your application.
Note: In both cases, the campaign operates differently than conventional session-level referrals. The campaign remains valid for the life of a given application, unless overwritten by a later campaign.
The Android 1.6 OS release supports the use of a referrer URL parameter in download links to the Android Market. 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="com.google.android.apps.analytics.AnalyticsReceiver" android:exported="true">
<intent-filter>
<action android:name="com.android.vending.INSTALL_REFERRER" />
</intent-filter>
</receiver>
Note: Only one BroadcastReceiver class can be specified per application. Should you need to incorporate two or more BroadcastReceivers from different SDKs, you will need to create your own BroadcastReceiver class that will receive all broadcasts and call the appropriate BroadcastReceivers for each type of Broadcast.
Note: Android Market Campaign Tracking now supports autotagging.
To set up Google Analytics campaign tracking through the Android market, 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, fill in the fields below. Package Name, Campaign Source, Campaign Medium, and Campaign Name are required. For a detailed description of each parameter, see the table below.
With version 1.3 of the Google Analytics SDK for Android, you can now track campaigns for sources other than Android Market. 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:
tracker.setReferrer(referrer);
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 AdWords. 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.
Note: Setting the referrer records a new session for the subsequent hit. For a detailed description of each parameter, see the table below.
| 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
utm_content=textlink
|
This release contains:
This release contains:
This release contains:
This release contains:
This release contains:
This release contains:
userAgent StringThis release contains: