Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Using Google Analytics in an Android Application

Author: Ashwini Shahapurkar -- Published? true -- FormatLanguage: W

Problem:

Often developers want to track their application in terms of features used by users. How can one find which feature is most used by the App's users?

Solution:

We can use Google Analytics to track the App based on defined criteria, similar to the website tracking mechanism.

Discussion:

Before we use Google Analytics in our app, we need an Analytics account and the Google Analytics SDK.

Download the Analytics SDK(2.0 as available at the time of writing this recipe) from http://code.google.com/mobile/analytics/download.html. Unzip the SDK and add libGoogleAnalytics.jar to your project's build path.

Add following permissions in your project's AndroidManifest.xml.

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Now, sign into your analytics account and create a website profile for the App. The website URL can be fake but shall be descriptive enough. It is suggested that you use the reverse package name for this. For example, if the application package name is com.example.analytics.test; then the website URL for this app can be http://test.analytics.example.com. After successful creation of website profile, a web property ID is generated for that profile. Note it down as we will be using this in our app. This web property ID, also known as UA number of your tracking code, uniquely identifies the website profile.

Note: You must mention in your App that you are collecting anonymous user data in your App to track your App.

After this setup, we are ready to track our application. Obtain the singleton instance of the tracker by calling getTracker() method on GoogleAnalytics object. This makes us ready to track the app activities & events as needed. Usually, we will want to track more than activities in the App. In such a scenario it is a good idea to have this tracker instance in OnCreate() method of the Application class of the app.

public class GADemoApp extends Application {

	/*define your web property ID obtained after profile creation for the app*/
	private String appId = "UA-XXXXXXXX-Y";
	
	/*Analytics instance*/
	GoogleAnalytics analyticsInstance;
	
	/*Analytics tracker instance*/
	Tracker tracker;

	@Override
	public void onCreate() {
		super.onCreate();
		
		//get the singleton tracker instance
		analyticsInstance = GoogleAnalytics.getInstance(getApplicationContext());
		tracker = analyticsInstance.getTracker(appId);
		GAServiceManager.getInstance().setDispatchPeriod(30);

		//your app specific code goes here
	}

	/* This is getter for tracker instance. This is called in activity to get reference to tracker instance.*/
	public Tracker getTracker() {
		return tracker;
	}

}

You can track pageviews and events in the activity by calling sendView() and sendEvent() methods on tracker instance.

public class MainActivity extends Activity 
{
    @Override
	protected void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
            
        //track the page view for activity
	    Tracker tracker = ((GADemoApp)getApplication()).getTracker();
		tracker.sendView("/MainActivity");

            /*You can track events like button clicks*/
            findViewById(R.id.actionButton).setOnClickListener(new View.OnClickListener() {
		@Override
		public void onClick(View v) {
  		    Tracker tracker = ((GADemoApp)getApplication()).getTracker();
				tracker.sendEvent("Action Event","Action Button", "Button clicked",0L);
				// Manually dispatch any queued hits.
				GAServiceManager.getInstance().dispatch();
		}
	     });
	//your stuff goes here	
    }
}

Remember, your events and pageviews will not be sent to the server until you call the dispatch() method on tracker. In this way we can track all the activities and events inside them. Note:Above method explains the way to track pageviews & events with advanced way. There is EasyTracker class available which can achieve the similar goals with minimum code & some configuration files.

See Also:

For getting started with GoogleAnalytics on android, you can check at https://developers.google.com/analytics/devguides/collection/android/v2/

Harshada 2013-03-29 02:14:05.938 Google analytic have update its jar file. pls updation is required. Waiting for updated source code. Thanks
sshraddha 2011-05-18 07:51:02.595 Very simple and useful recipe. The most common and very important feature.
prupwal 2011-05-10 23:59:14.286 Nice information!!