Event Tracking with Analytics API v4 for Android

As I’ve learned from developing my own mileage tracking app for cyclists and commuters, getting ratings and feedback from users can be challenging and time consuming. Event tracking can help by enabling you to develop a sense of how popular a particular feature is and how often it’s getting used by users of your app.

In Android, Google Play Services’ Analytics API v4 can be used to gather statistics on the user-events that occur within your app.  In this post I’ll quickly show you how to use this API to accomplish simple event tracking.

Getting started.

It’s important to say at this point that all of these statistics are totally anonymous. App developers who use analytics have no idea who is using each feature or generating each event, only that an event occurred.

Assuming you’ve set up Google Analytics v4 in your app as per my last post, tracking app events is fairly simple. The first thing you need is your analytics application Tracker (obtained in my case by calling getApplication() as per the previous post). Bear in mind that this method is only available in an object that extends Android’s Activity or Service class so you can’t use it everywhere without some messing about.

Once you have your application Tracker you should use an analytics EventBuilder to build() an event and use the send() method on the Tracker to send it to Google. Building an event is easy. You simply create a new HitBuilders.EventBuilder, setting a ‘category’ and an ‘action’ for your new event.

Sample code.

The sample code below shows how I track the users manual use use of the ‘START’ button in Trip Computer. I have similar tracking events for STOP and also for the use of key settings and features like the activation of the app’s unique ‘battery-saver’ mode (which I understand is quite popular with cyclists).

// Get an Analytics Event tracker.
Tracker myTracker = ((TripComputerApplication) getApplication())

// Build and Send the Analytics Event.
myTracker.send(new HitBuilders.EventBuilder()
.setCategory("Journey Events")
.setAction("Pressed Start Button")

Once the events are reported back to Google, the Analytics console will display them in the ‘Behaviour > Events > Overview’ panel and display a simple count how many times each event was raised within the tracking period. You can also further subdivide the actions by setting a ‘label’ or by providing a ‘value’ (but neither of these is actually required).

More information.

For more information see the following articles:-


About the Author

Ben Wilcock is the developer of Trip Computer, the only distance tracking app for Android with a battery-saving LOW POWER mode. It’s perfect for cyclists, runners, walkers, hand-gliders, pilots and drivers. It’s free! Download it from the Google Play Store now:-

Get Trip Computer on Google Play

Working with Google Analytics API v4 for Android

For v4 of the Google Analytics API for Android, Google has moved the implementation into Google Play Services. As part of the move the EasyTracker class has been removed, but it still possible to get a fairly simple ‘automatic’ Tracker up and running with little effort. In this post I’ll show you how.

  • You’re already using the Google Analytics v3 API EasyTracker class and just want to do a basic migration to v4 – or –
  • You just want to set up a basic analytics Tracker that sends a Hit when the user starts an activity
  • You already have the latest Google Play Services up and running in your Android app

Let’s get started.

Because you already have the Google Play Services library in your build, all the necessary helper classes will already be available to your code (if not see here). In the v4 Google Analytics API has a number of helper classes and configuration options which can make getting up and running fairly straight forwards, but I found the documentation to be a little unclear, so here’s what to do…

Step 1.

Create the following global_tracker.xml config file and add it to your android application’s res/xml folder. This will be used by GoogleAnalytics class as it’s basic global config. You’ll need to customise screen names for your app. Note that there is no ‘Tracking ID’ in this file – that comes later. Of note here is the ga_dryRun element which is used to switch on or off the sending of tracking reports to Google Analytics. You can use this setting in debug to prevent live and debug data getting mixed up.

<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools" tools:ignore="TypographyDashes">

<!-- the Local LogLevel for Analytics -->
<string name="ga_logLevel">verbose</string>

<!-- how often the dispatcher should fire -->
<integer name="ga_dispatchPeriod">30</integer>

<!-- Treat events as test events and don't send to google -->
<bool name="ga_dryRun">false</bool>

<!-- The screen names that will appear in reports -->
<string name="com.mycompany.MyActivity">My Activity</string>

Step 2.

Now add a second file, “app_tracker.xml” to the same folder location (res/xml). There are a few things of note in this file. You should change the ga_trackingId to the Google Analytics Tracking Id for your app (you get this from the analytics console). Setting ga_autoActivityTracking to ‘true’ is important for this tutorial – this makes setting-up and sending tracking hits from your code much simpler. Finally, be sure to customise your screen names, add one for each activity where you’ll be adding tracking code.

Step 3.

Last in terms of config, modify your AndroidManifest.xml by adding the following line within the ‘application’ element. This configures the GoogleAnalytics class (a singleton whick controls the creation of Tracker instances) with the basic configuration in the res/xml/global_tracker.xml file.

<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools" tools:ignore="TypographyDashes">

<!-- The apps Analytics Tracking Id -->
<string name="ga_trackingId">UX-XXXXXXXX-X</string>

<!-- Percentage of events to include in reports -->
<string name="ga_sampleFrequency">100.0</string>

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

<!-- catch and report uncaught exceptions from the app -->
<bool name="ga_reportUncaughtExceptions">true</bool>

<!-- How long a session exists before giving up -->
<integer name="ga_sessionTimeout">-1</integer>

<!-- If ga_autoActivityTracking is enabled, an alternate screen name can be specified to substitute for the full length canonical Activity name in screen view hit. In order to specify an alternate screen name use an <screenName> element, with the name attribute specifying the canonical name, and the value the alias to use instead. -->
<screenName name="com.mycompany.MyActivity">My Activity</screenName>

That’s all the basic xml configuration done.

Step 4.

We can now add (or modify) your application’s ‘Application’ class so it contains some Trackers that we can reference from our activity…

package com.mycompany;

import android.app.Application;

import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.Tracker;

import java.util.HashMap;

public class MyApplication extends Application {

// The following line should be changed to include the correct property id.
private static final String PROPERTY_ID = "UX-XXXXXXXX-X";

//Logging TAG
private static final String TAG = "MyApp";

public static int GENERAL_TRACKER = 0;

public enum TrackerName {
APP_TRACKER, // Tracker used only in this app.
GLOBAL_TRACKER, // Tracker used by all the apps from a company. eg: roll-up tracking.
ECOMMERCE_TRACKER, // Tracker used by all ecommerce transactions from a company.

HashMap<TrackerName, Tracker> mTrackers = new HashMap<TrackerName, Tracker>();

public MyApplication() {

synchronized Tracker getTracker(TrackerName trackerId) {
if (!mTrackers.containsKey(trackerId)) {

GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
Tracker t = (trackerId == TrackerName.APP_TRACKER) ? analytics.newTracker(R.xml.app_tracker)
: (trackerId == TrackerName.GLOBAL_TRACKER) ? analytics.newTracker(PROPERTY_ID)
: analytics.newTracker(R.xml.ecommerce_tracker);
mTrackers.put(trackerId, t);

return mTrackers.get(trackerId);

Either ignore the ECOMMERCE_TRACKER or create an xml file in res/xml called ecommerce_tracker.xml to configure it. I’ve left it in the code just to show its possible to have additional trackers besides APP and GLOBAL. There is a sample xml configuration file for the ecommerce_tracker in <your-android-sdk-directory>\extras\google\google_play_services\samples\analytics\res\xml but it simply contains the tracking_id property discussed earlier.

Step 5.

At last we can now add some actual hit tracking code to our activity. First, import the class com.google.android.gms.analytics.GoogleAnalytics and initialise the application level tracker in your activities onCreate() method. Do this in each activity you want to track.

//Get a Tracker (should auto-report)
((MyApplication) getApplication()).getTracker(MyApplication.TrackerName.APP_TRACKER);

Then, in onStart() record a user start ‘hit’ with analytics when the activity starts up. Do this in each activity you want to track.

//Get an Analytics tracker to report app starts and uncaught exceptions etc.

Finally, record the end of the users activity by sending a stop hit to analytics during the onStop() method of our Activity. Do this in each activity you want to track.

//Stop the analytics tracking

And Finally…

If you now compile and install your app on your device and start it up, assuming you set ga_logLevel to verbose and ga_dryRun to false, in logCat you should see some of the following log lines confirming your hits being sent to Google Analytics.

com.mycompany.myapp V/GAV3? Thread[GAThread,5,main]: connecting to Analytics service
com.mycompany.myapp V/GAV3? Thread[GAThread,5,main]: connect: bindService returned false for Intent { act=com.google.android.gms.analytics.service.START cmp=com.google.android.gms/.analytics.service.AnalyticsService (has extras) }
com.mycompany.myapp V/GAV3? Thread[GAThread,5,main]: Loaded clientId
com.mycompany.myapp I/GAV3? Thread[GAThread,5,main]: No campaign data found.
com.mycompany.myapp V/GAV3? Thread[GAThread,5,main]: Initialized GA Thread
com.mycompany.myapp V/GAV3? Thread[GAThread,5,main]: putHit called
com.mycompany.myapp V/GAV3? Thread[GAThread,5,main]: Dispatch running...
com.mycompany.myapp V/GAV3? Thread[GAThread,5,main]: sent 1 of 1 hits

Even better, if you’re logged into the Google Analytics console’s reporting dashboard, on the ‘Real Time – Overview’ page, you may even notice the following…

Real Time Overview page
Analytics Real Time Overview page

Next time…

In my next post I’ll show you how to use event tracking to gain extra feedback your users.

About the Author

Ben Wilcock is author of Trip Computer, the only distance tracking app for Android with a LOW POWER mode. It’s perfect for cyclists, runners, walkers, hand-gliders, pilots and drivers. It’s free! Download it from the Google Play Store now:-

Get Trip Computer on Google Play

Announcing: Trip Computer for Android

The reason that I’ve been so bad a posting recently is that I caught the Android development bug. I’ve been using all my spare time working on a new Android application called ‘Trip Computer’.

Trip Computer is a cost and distance tracker that you can use to help with business mileage expenses, or for leisure any time you want to know how far you’ve travelled, which direction you’ve been going in or how long you’ve been going. You can use it walking, cycling, running, in the car, on the train or even on boats or planes (subject to the usual flight restrictions).


Working with Android has been the most brilliant experience, it really is very cool. I’ve also been exclusively using the new Android Studio IDE from Google (pre-beta) including it’s built in Gradle build system.

Android Studio is really good. Announced at last years Google I/O conference it’s based on IntelliJ Idea Community Edition and already it’s giving Eclipse a real run for its money with its strong integration into the Android eco-system. The learning curve has been quite forgiving and the IDE quality and stability are very surprising considering its not a fully released product.

Gradle is a different story. I can take it or leave it to be honest. As a Maven user, I can see lots of issues and nasty cludges (like the poor file ‘filter’ and replace experience which is really useful and much better in Maven). The learning curve has been steep, possibly because Android projects are not standard Java projects. But no pain no gain as they say and I do feel like I’ve come out the other side stronger and more flexible as a result.

I did pick up some handy Android hints and tips along the way, which no doubt I’ll share when I get more time.

You can download the full app for free and try it out for yourself. It’s fairly simple in UI / UX terms, but hopefully it’s got enough features to be a fun addition you your phone or tablet. I’ve tried to support the widest range of devices possible so anything with Froyo onwards and the right hardware should be just fine…

Get it on Google Play

My all-time top five posts

I’ve just been picking through the admin statistics for my blog and I thought I’d quickly share with everyone the top 5 posts from my SOA, Java and BPM blog.

Every year I’m astonished by the level of support that I receive from the architecture community, and yet looking at the stats one thing has surprised me. Considering that I’m a SOA specialist, none of the top 3 articles contain pure SOA content. It seems that it’s more likely that developers interested in SOA and service-oriented software are the most regular and common visitors to my blog and most often they’re after tips of a technical nature relating to application servers, cloud infrastructure and other service implementation tips.

In the more architectural content, my tips for getting started using Business Process Modelling Notation come out on top.

The top three articles to date were:

  1. Hyperjaxb3: XML to Java to Database (and back again)
  2. Commissioning Glassfish 3 application servers on AWS EC2
  3. Getting Started with BPMN
  4. RESTful service with HyperJaxb3 (Part 4 – Architecture)
  5. SOA Certified Architect: Module 1 – Fundamental SOA & Service-Oriented Computing

So if you haven’t seen them before, follow the links above. Several thousands visitors can’t be wrong.

In future I’ll try to post more development tips. Next on my R&D agenda is Android development, so we’ll see what inspiration that offers for future articles.

As ever, thanks for reading!

Want up to the minute news? You can follow me on Twitter, G+ and LinkedIn.

Book review: SOA Made Simple – Packt Publishing

SOA made Simple_covPackt Publishing’s latest SOA book: ‘SOA Made Simple‘, claims to lay bare the fundamental strategies, goals, principals, benefits and impacts of service oriented architecture in a way that is easily accessible. In this review we’ll see if these claims are justified, and if they are, what it might mean for the SOA community as a whole.

As a certified SOA Architect, I’m often surprised by how difficult it is for companies to create a shared consensus and understanding of what it means to become service-oriented and how important it is for the future survival of commercial and non-commercial organisations alike. Many of these difficulties are related to two basic issues: lack of knowledge and lack of experience. This book intends to help alleviate both.

The authors (Lonneke Dikmans & Ronald van Luttikhuizen) certainly have the knowledge and the experience required to create successful SOA implementations. Fortunately for us, they also have have a fluid and easy to read writing style and the advice that they dispense in this book is accurate, valuable, practical, consistent and of a very high standard throughout.

Many of my SOA gotcha’s are dealt with in the text. Registries aren’t for everyone, tick. ESB’s can be good for some use cases, but using them for EAI is a backwards step, tick. Canonical models are essential for broad-brush interoperability, tick. Data standards can be useful internally sometimes, but often more so at enterprise boundaries, tick.

Setting the scene.

In the preface, the book identifies the types of people that it is intended to help: Architects, Designers, Developers, and Team-leads involved in delivering SOA.  However, I would go much further. I think this book would also be of use to many of the UK’s CIO’s, CTO’s, IT Directors, Enterprise Architects, Department Managers, Project Managers and Programme Managers. Basically anyone who is new to SOA but has some responsibility to deliver it within their enterprise.

The book begins with a chapter that discusses the problems faced by modern businesses, most of which stem from a lack of alignment between business and IT leading to an increased exposure to risk. Duplication of functionality and data in application (and process) ‘silos’ is also identified as a common issue. These two themes are revisited throughout the book using various example case studies.

The following chapter covers Service-Orientation as a solution to these problems. It starts by discussing the SOA architectural style but quickly moves on to services, discussing what a service is and how services can be described using the concepts of contracts, interfaces and implementations (these three being separate facets of the same service).

Service Inventory, Service Design & Service Implementation.

Chapter three discusses the logical starting point for any service inventory: service identification and service design.  It uses simple business process models to illustrate the activities and decision making points in the process (as do I when working with my corporate clients). Top-down, bottom-up and meet-in-the-middle design approaches are covered in detail, with their respective advantages and disadvantages made clear. A set of service design principals are offered, but one of the few criticisms I have is that these are not simply taken from Thomas Erl’s more definitive SOA Principals of Service Design (albeit re-written to make them more accessible to the layperson).

Chapter four discusses the process of ‘classifying’ (grouping & typing) services, and offers a simple classification system that introduces three basic service types: Elementary services, composite services and process services. It’s not a classification system that I’ve used personally (I usually use Erl’s) but I will be considering it in future for use with clients thanks to the additional simplicity it affords.

SOA Platforms are discussed in chapter five with a look at the common building blocks of service oriented enterprise architectures and the technologies that support them. Services, events, compositions, rules, UI’s, security, registry & repository and design & development tooling are all examined and their associated technologies identified and explained (for example: application servers for hosting services, ESB’s for exposing endpoints, etc.). Chapter six then goes on to explore the platforms and components offered by the big three SOA vendors (Oracle, IBM and Microsoft).

Management and Politics.

The latter third of the book is devoted to what I call the ‘management and politics of SOA implementation’. First up is a section on how to create a viable SOA business case and migration roadmap, including an examination of SOA investment choices using basic business scenarios such as cost-cutting or reduced time to market. The reader is also warned about the naturally wavering enthusiasm for SOA as complicated change programmes progress through various emotionally charged stages experiencing both euphoria and despair.

Chapter eight covers the important topic of SOA life-cycle management, whilst chapter nine continues this thread with a discussion on SOA Governance.

In life-cycle management, the authors elaborate on techniques for versioning services and for the management of various service related artefacts (contracts, implementations, etc.). Registries and repositories are explained and their differences noted, alongside some refreshingly practical advice from an enterprise level book of this kind – namely that registries are often not required and repositories can be provided using the simplest of tools (if you’ve seen my InfoQ article on Simple Service Repositories and you’ll already know I’m a strong advocate of this approach).

When discussing SOA Governance, the authors suggest a strategic approach when ‘picking your battles’ – choosing which principles and practices to protect and which can be sacrificed for the greater good. Governance, they say, is about protecting the SOA strategy by guiding and influencing the architectural design choices and remaining outcome-oriented. There are many ways to tie a shoe-lace they say, the important thing is that the shoe stays on! Deviations are sometimes necessary, but they should always be recorded, monitored and corrected at the most suitable juncture available. I couldn’t agree more. It’s a sensible approach to an important SOA practice that’s often misaligned, misinterpreted, misunderstood or simply missed out.

The final section is devoted to methodologies and SOA. Europe’s most commonly used methodologies for demand management (business change), project management, IT management and development are all examined and SOA’s impacts on their processes and practices are explained. Modern SOA (what the management consultants now refer to as ‘digital business’) supersedes most of these methodologies, so it’s good that the authors have taken the time to explain where conflicts in approach may arise and what you can do about them.

My Summary.

As you may have already noticed, I really liked this book. Personally, I think it should be the minimum required reading for any Architect, Developer or Project Manager who adds ‘SOA’ to their profile. Let me explain why…

People who genuinely ‘get SOA’ understand that becoming service-oriented means realising a new strategic design direction for both business and architecture alike. It’s not simply about web service technology. That’s very much the underlying theme of this particular book. It provides the reader with clear information regarding the business motivation behind SOA and then backs up this new found understanding with some insights regarding the tools and technology used to support this new architectural design paradigm.

However, over the years I’ve met a small number of ‘SOA Charlatans’ – people who are ‘a bit vague’ on the motivation and business benefits behind SOA, but figured that they would go and get a SOA job anyway because they’ve “done loads of integration” or because “no-one understands SOA, so why not?”. In the past, this ‘SOA bluff’ strategy probably worked in many cases, but from now on beware – if the interviewer has read and understood just a fraction of this book, they’ll tear these imposters to pieces!

That’s my two-cents, what’s yours? Leave a comment or share…

About the Reviewer:

Ben Wilcock is a freelance SOA Certified Architect with a reputation for delivering exceptional Service Oriented Architectures. You can read his blog at https://benwilcock.wordpress.com/ or contact him via twitter (@benbravo73) or via his company website at http://www.soagrowers.com/.

Continue reading “Book review: SOA Made Simple – Packt Publishing”

SOA Service & Microservice Design Cheat Sheet

This simple cheat sheet contains all the key goals, principals and design patterns that you should be aware of when designing services or microservices for SOA. It also and contains helpful links to places where you can find more in-depth information on each topic.

Continue reading “SOA Service & Microservice Design Cheat Sheet”