Wednesday, 27 April 2011

Integrating Google Analytics into Android

One of the many things on my development list for the current Android projects I'm developing has been to integrate some form of user tracking/feedback functionality into the application.

Ill show you how I went about integrating Google Analytics into a sample application explaining some of the reasons and decisions I took along the line.

API's/Library

After a quick Google and a little bit of reading there seems to be a serious lack of available Google Analytics API's for android. One alternative is a paid Analytics tool from usermartix but since its not free it doesn't really help me for the example so I'm sticking with Google's own Analytics SDK for Android.

Prerequisite

I'm going to presume you have eclipse or a similar IDE installed with the Android SDK and IDE plugin set-up and installed. Installation instructions are available in the getting started section of the Google Mobile SDK docs.

For this example the code will work on Android 1.6 and above (a.k.a Donut) All code can be found at my GitHib repository @ https://github.com/jamesemorgan/AndroidGoolgeAnalyticsDemo


Getting Started


1) First create a new "Android Project" in Eclipse giving your application a name, package structure and specifying Android 1.4, API level 4.

If you haven't create an Android Emulator yet, plenty of information can be found on-line but the best way is to use the AVD manager which gets installed with the SDK and can be launched directly from eclipse.

2) Download the Google Analytic SDK, unzip it and place the jar in your libs folder or simply add it to your build path of the project as seen to the left.

3) Add the following lines to your AndroidManifest.xml file in order to enable to use of the Internet when you deploy your application. An exception will be thrown if not.









Creating Your Abstract Activity

I've done this in other projects and it simply encapsulates your Google Analytics code in a super class. This just means you can make all your other activities extend this class and thus reduce the need to for duplicate Analytics code in ever Activity you want to track. Since Android is based on the activity model it seems like the most appropriate solution for encapsulating this logic. 


public class AbstractAnalyticActivity extends Activity {

 private GoogleAnalyticsTracker tracker;

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

  // Get and set the Google Analytic tracker instance
  setTracker(GoogleAnalyticsTracker.getInstance());

  // Get application shared preferences
  final SharedPreferences preferences = getSharedPreferences("SomeSharedPreferenceKey", Activity.MODE_PRIVATE);

  // Get your preference key for enabling google analytics
  final boolean enabledGoogleAnaltyics = preferences.getBoolean("PREF_GOOGLE_ANALYTIC", true);

  if (enabledGoogleAnaltyics) {

   // Arg1: Your tracking ID
   // Arg2: How often your tracking events get dispatched to google, set to 20 seconds
   // Arg3: The activity to track
   tracker.start("UA-XXXXXXXX-X", 20, this);
  }
  else {
   // Stop the tracker if not enabled
   tracker.stop();
  }
 }

 private void setTracker(final GoogleAnalyticsTracker tracker) {
  this.tracker = tracker;
 }

 public GoogleAnalyticsTracker getTracker() {
  return this.tracker;
 }
}


Above is the class I created to encapsulate all Google Analytic logic. 

  • First create a GoogleAnalyticsTracker variable, with a public getter and private setter thus to only allow subclass's the ability to retrieve the tracking class. 
  • Secondly, as with most Android Activities you must override the onCreate method which is where I place all set-up code for the Google Analytic tracker. 
  • Replace UA-XXXXXXXX-X with your Google Analytics account ID.  Again plenty of instructions/guides online can be found on how to do this.
  • In addition to any Analytics code I have also included an example of how to retrieve  application user preferences in order to give the user the ability to disable tracking if they wish so. (Lines 13-16) I believe this should always be the case when tracking a users movement you should always give them the option to not be tracked. I believe visibility and trust is key to a successful user/developer relationship.
Define your Activities XML


For this example I simply have four buttons on my screen each one symbolising how a user many navigate between different sections of your application. One of the recommended design practices is to create an opening dashboard. Each button is defined as seen below. Notice the onClick Handler, we will use this later for tracking which parts of the application a user navigates to. Simply modify the default main.xml file created for you by eclipse and add the buttons shown below.









 

 
  
  
 

 

  
  
 



Create your Activity

Next step is to create the activity you want to track, for the purpose of the this example I've  called mine AndroidAnalyticsDemoActivity and extends the Abstract Activity mentioned earlier. Add your onClick listeners as defined before, and ensure you call the super class onCreate method or an exception will be thrown.
In order to track an event, I simply retrieve the tracker from the parent class and set what page view I want the tracking to be registered as. I've done this for each button declared in the main.xml file mentioned earlier.

Don't forget that Google Analytics is 24 hours behind and will not show you any analytics data straight away. Don't be surprised if your newly created account doesn't show anything straight away.



public class AndroidAnalyticsDemoActivity extends AbstractAnalyticActivity {

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

  // Set you main view, i.e. your GUI xml file
  setContentView(R.layout.main);
 }

 public void onStatsClickgetTracker().trackPageView("/DashboardStatsActivity");
 }

 public void onGroupsClick(final View v) {
  getTracker().trackPageView("/DashboardGroupsActivity");
 }

 public void onFriendsClick(final View v) {
  getTracker().trackPageView("/DashboardFriendsActivity");
 }

 public void onHomeClick(final View v) {
  getTracker().trackPageView("/DashboardHomeActivity");
 }

 @Override
 protected void onDestroy() {
  super.onDestroy();
  // Stop the tracker when it is no longer needed.
  getTracker().stop();
 }
}

Conclusion
Google Analytics provides a quick and simple way of tracking application views and events inside your Android application. I've only shown you how to track page views but as with most things, a plethora of information is available on the Internet about this useful and intuitive API.