Integrating Google Analytics SDK (V2) with Android

The Google Analytics SDK for Android makes it easy for developers to collect valuable statics about how the users are using their app.

Here are some features that Android Google Analytics SDK offers:

  • The number of active users that are using the application
  • Usage of specific features
  • The number and type of application crashes
  • From where in the world the application is used
  • And many other useful metrics.

Just to illustrate the integration process lets create a simple proof of concept application with 2 activities: MainActivity and AboutActivity, and 2 buttons: Rate and Share.

Our mission is to integrate Google Analytics SDK with the application, to:

  • track activity views, (MainActivity and About)
  • track events (how many times the buttons “Rate”, and “Share” are clicked)

android google analytics sdk

If you are searching for Google Analytics I’m assuming you are already pretty familiar with Android and could create the proof of concept application yourself, so I will skip this step and concentrate solely on integration.

 

1. Downloading the SDK

Go to downloads page and download GoogleAnalyticsAndroid.zip Version 2.0. Extract the archive and add libGoogleAnalyticsV2.jar to your project’s /libs directory.

At the moment of writing this post, Google provides two versions: version 1.5.1 (legacy), and version 2.0 beta. Still if the Version 2 of SDK is beta, I highly suggest you choose this version, over the 1.5.1 (legacy).
The reason not to choose SDK 1.5.1 is that it uses a tracking model that is designed to track visitors to traditional websites and interaction with widgets in traditional web pages.

The new “App” profiles and reports will only accept data from version 2 or higher of the SDK.

 

2. Creating a Google Analytics account

Before starting to use the SDK you first must create an account at: http://www.google.com/analytics/

  1. Sign in to your account.
  2. Click Admin.
  3. Click Account list (just below the menu bar)
  4. Click +New Account
  5. When asked what you would like to track, select App property.android app profile
  6. Enter all the necessary information and click Get Tracking ID.

Now that you have a Tracking ID, you can begin the integration with the application. The first step is to update the AndroidManifest file.

 

3. Updating AndroidManifest file.

Add folowing permissions to the AndroidManifest file:

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

 

4. Creating the analytics.xml file

In version 2 of Google Analytics SDK for Android, the tracking settings are managed from an xml resource file called: analytics.xml. You will need to create this file in res/values directory, and add your tracking ID as well as other settings here.


<?xml version="1.0" encoding="utf-8"?>
<resources>

   <!-- Replace placeholder ID with your tracking ID -->
   <string name="ga_trackingId">UA-00000000-0</string>

   <!-- Enable Activity tracking -->
   <bool name="ga_autoActivityTracking">true</bool>

   <!-- Enable debug -->
   <bool name="ga_debug">true</bool>

   <!-- The screen names that will appear in your reporting -->
   <string name="com.testgoogleanalytics.MainActivity">MainActivity</string>
   <string name="com.testgoogleanalytics.About">About</string>

   <!--
   The inverval of time after all the collected data
   should be sent to the server, in seconds.
   -->
   <integer name="ga_dispatchPeriod">30</integer>

</resources>

 

5. Tracking activities.

To track activities add the tracking methods to the onStart() and onStop()  of each of your activities.


// Example of tracking MainActivity
public class MainActivity extends Activity {
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }

   @Override
   protected void onStart() {
      super.onStart();
      EasyTracker.getInstance().activityStart(this); // Add this method
   }

   @Override
   protected void onStop() {
      super.onStop();
      EasyTracker.getInstance().activityStop(this); // Add this method
   }
}

One thing to note here is that EasyTraker requires a context before you can use it. If you attempt to call any of its methods but did not pass first a context, you may end up with an IllegalStateException.

In the above example, in  the onStart()  and onStop() methods the context is passed as an argument to activityStart() and activityStop(), but  if you need to make EasyTracker calls in other classes or methods, you’ll need to call EasyTracker’s setContext(Context context) method first:

Context context= this;  // Get current context.
EasyTracker.getInstance().setContext(context);  // Set context
// EasyTracker is now ready for use.

 

6. Tracking events

Tracking events is just as easy as tracking activities, you just need a Tracker object and call the trackEvent(String category, String action, String label, int value) method.

public class MainActivity extends Activity {

   private Tracker tracker;

   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      // Set context
      EasyTracker.getInstance().setContext(getApplicationContext());
      // Instantiate the Tracker
      tracker = EasyTracker.getTracker();

      // Add tracking functionality to "Rate" button
      Button rate = (Button) findViewById(R.id.rate);
      rate.setOnClickListener(new OnClickListener() {
         @Override
         public void onClick(View arg0) {
            // The rest of your code
            tracker.trackEvent("Buttons Category", "Rate", "", 0L);
         }
      });

      // Add tracking functionality to "Share" button....
   }
}

In this particular example I don’t need a label nor a value, that is why I set for the last 2 parameters of trackEvent() method, an empty string a 0 (zero), but depending of your needs you may populate them with some data.

 

7. Debugging

Debugging helps you deal with troubleshooting, and make you sure that the data actually is sent to the server. To set the Google Analytics in debug mode, add the following setting in the analytics.xml


<bool name="ga_debug">true</bool>

Once your are in debug mode, you can watch the log information in LogCat:

 

Waiting for the big moment!

If everything is configured correctly, the reports should appear on live. Usually it takes about 24 hours to see the data in your account.

android actions google analytics

 

 

What happens if my application is used when no network is available?

Just in case you asked this yourself…, all the events are persisted in a local storage, and they will be sent the next time your app is running and dispatch is called.

 

Last but not least

One important thing not to be forgotten: 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.

Android Google Analytics SDK offers more than tracking activities and events, see: https://developers.google.com/analytics/devguides/collection/android/v2/ to get the most out of it.

Please visit the Android Tutorials page for more tutorials.

Advertisement

How to verify an RSS Feed if New Articles have been published.

Recently I built an rss app for a site that publishes daily IT News – ITMoldova.com. The main feature of application is to launch a service in background (at a given interval of time), and check if new articles have been published on http://itmoldova.com site. If it turns out that new articles have been published, then fire a notification message and notify the user about this, something like this: “4 New Articles Published on ITMoldova.com”.

How to identify how many articles were published?

The mechanism to identify if new articles have been published on the site (and how many) is pretty straightforward: when the application is installed and launched for the first time, it parses the Rss Feed and creates a new entry in the SharedPreferences with the value of <pubDate> element, of the first item from the rss list (pubDate = publication date). Then, everytime the service starts, it parses the RSS Feed and checks the value of first item from the rss list against the value stored in SharedPreferences, if the value stored in SharedPreferences is less than value returned by the service, then it means that there are new articles and it’s time to notify the user! Lastly, update the SharedPreferences with the most recent pubDate.

For the sake of simplicity and keeping things consistent, I will post here only snippets of most relevant code, but this will be good enough to give you an idea about how things works.

How to compare two dates?

To compare the dates we need to convert them to milliseconds. The getTime() method of Date class can help us return the number of milliseconds of a given date:

Date date=new Date();
int timeMilliseconds=date.getTime();

 

Below is the implementation of verifyDates(String, String) method that will be used by the Service. The method takes 2 string parameters, the pubDate of rss item, and the pubDate stored in SharedPreferences.


public class Tools {
  public int newArticles;
  public boolean hasMoreArticles = true;

  public void verifyDates(String rssPubDate, String sharedPrefLastPubDate) {
    if (hasMoreArticles) {
      SimpleDateFormat df = new SimpleDateFormat("dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
      Date dLastPubDate = null;
      Date dRssPubDate = null;

      try {
        dLastPubDate = df.parse(sharedPrefLastPubDate.substring(5));
        dRssPubDate = df.parse(rssPubDate.substring(5));
      } catch (ParseException e) {
        Log.d("GREC", "Exception in verifayDates: " + e.getMessage());
        e.printStackTrace();
      }

      //We want to count how many new articles were published.
      if (dRssPubDate.getTime() > dLastPubDate.getTime()) {
        newArticles++;
      } else {
        hasMoreArticles = false;
      }
    }
  }

}
The Service Implementation

The service will parse the Rss Feed and do the comparison. Also, it will launch a status bar notification if it turns out that new articles were published.

public class RssService extends IntentService {

  public RssService() {
    super("ITMoldovaRssService");
  }

  @Override
  protected void onHandleIntent(Intent intent) {

    // Retrieve the date from SharedPreferences
    String lastPubDate = getDateFromSharedPrefs();

    // The AndroidFeedParser class helps us parse the Rss Feed.
    AndroidFeedParser parser;

    try {
      parser = new AndroidFeedParser(new URL("http://itmoldova.com/feed/"));
      List<Message> list = parser.parse();

      if (list != null) {
        for (int i = 0; i < list.size(); i++) {

          // Verify the pubDate of each item, against pubDate stored in SharedPreferences
          tools.verifyDates(list.get(i).getDate(), lastPubDate);
        }

        // Get the last pubDate and save it to SharedPreferences.
        lastPubDate = list.get(0).getDate();
        saveToSharedPreferences(lastPubDate);
      }
    } catch (MalformedURLException e) {
      Log.d("GREC", "Malformed URL Exception: " + e.getMessage());
      e.printStackTrace();
    }

    if (tools.newArticles > 0) {
      displayNotification();
    } else {
      Log.d("GREC", "No new articles ");
    }
  }
}

 

The service begins with parsing the Rss Feed and return the list of items:

List<Message> list = parser.parse();

then iterate through it comparing the publication date:

for (int i = 0; i < list.size(); i++) {
    // Verify the pubDate of each item, against pubDate stored in SharedPreferences
    tools.verifyDates(list.get(i).getDate(), lastPubDate);
}

and then ends getting the most recent publication date and saving it to SharedPreferences:

// Get the last pubDate and save it to SharedPreferences.
lastPubDate = list.get(0).getDate();
saveToSharedPreferences(lastPubDate);

If it turns out that new articles were published, display a status bar notification.

if (tools.newArticles > 0) {
displayNotification();
}

 

How to parse an XML feed and how to display a status bar notification are some helper topics you may need to take a look in order to fully complete this task.

Defining Global Variables in Android

At some point in your development process you may need to have several variables across application.

In this post I want to describe 2 ways through you can define global variables in Android: using a singleton class, and by extending the Android’s Application class.

1. Using a Singleton class

One of the simplest ways (it does not mean that is one of the best) to have global variables is to declare a singleton class:

public class Globals{
   private static Globals instance;

   // Global variable
   private int data;

   // Restrict the constructor from being instantiated
   private Globals(){}

   public void setData(int d){
     this.data=d;
   }
   public int getData(){
     return this.data;
   }

   public static synchronized Globals getInstance(){
     if(instance==null){
       instance=new Globals();
     }
     return instance;
   }
}

To use this class you get an instance first, and then do what you want with data:

Globals g = Globals.getInstance();
g.setData(100);

....
int data=g.getData();

Notice that we do not instantiate the object by calling “new”, in fact this wouldn’t be allowed as we declared the constructor private, so its not visible. Instead we call the getInstance() method and return our static object.

2. By Extending the Application class

The second way to define global variables is by extending the Application class. This is the base class for maintaining global application state.

a) Create a new class that extends Application.

public class Globals extends Application{
   private int data=200;

   public int getData(){
     return this.data;
   }

   public void setData(int d){
     this.data=d;
   }
}

b) Add the class to the AndroidManifest file as an attribute of <application> tag:

<application
   android:name=".Globals"
   .... />

c) Then you can access your global data from any Activity by calling getApplication()

Globals g = (Globals)getApplication();
int data=g.getData();

 

I said that using the Singleton pattern it’s one of the simplest ways to define global variables, but I mentioned also that it does not mean that it’s one of the best ways to do it. In fact this is quite a controversial subject.

You may believe that when a static variable is initialized it stays so for the entire life of the application, however this does not seem to be true everytime. Sometimes, there are situations when some static variables bound to activities happens to be uninitialized even they have been initialized.

This makes the static singleton approach not one of the best for keeping global variables, though the official Android documentation seems to encourage using them: “There is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way.”