Android Core

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.
 
 
 
 
 
 
 

Assumptions:

  • 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" <span style="line-height: 1.5; font-style: inherit; font-weight: inherit;">tools:ignore="TypographyDashes"></span>

<!-- 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>
</resources>

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.

<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools" <span style="line-height: 1.5; font-style: inherit; font-weight: inherit;">tools:ignore="TypographyDashes"></span>

<!-- 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>

</resources>

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.

<!-- Google Analytics Version v4 needs this value for easy tracking -->
<meta-data android:name="com.google.android.gms.analytics.globalConfigResource"
android:resource="@xml/global_tracker" />

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() {
super();
}

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 \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 & uncaught exceptions etc.
GoogleAnalytics.getInstance(this).reportActivityStart(this);

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
GoogleAnalytics.getInstance(this).reportActivityStop(this);

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…

Analytics Real Time Overview page
Analytics Real Time Overview page

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

15 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
pc
pc
9 years ago

Thanks for the concise example. Very helpful!

The XML in steps 1 & 2 have a syntax error. The beginning field isn’t closed properly.

In addition, R.xml.ecommerce_tracker isn’t defined in your example. It’s easy enough to add an ecommerce_tracker.xml but it may be worth mentioning to reduce confusion.

Ben Wilcock
9 years ago

Hi PC,

Thanks for spotting these issues, i’ve corrected them in the original blog post at http://benwilcock.wordpress.com/2014/04/11/working-with-google-analytics-api-v4-for-android.

The xml tags had been corrupted by the wordpress page editor, the sections shouldn’t be there. I’ve referenced google’s sample config for the ecommerce_tracker but left the listing out of the post for brevity because it doesn’t contain much so it doesn’t add much in the way of value.

Hopefully JCG will pick up the changes soon…

Cheers

Ben

Ayu
Ayu
9 years ago

Hi, Ben.
I have tried your step to analytic android in google analytic.
But im still have an error.
When i import libGoogleAnalyticService.jar, it’s not read on my app.
I mean, when i type :

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

in my activity, the error is “Cannot resolve symbol analytic”. Could you tell me what happen? Or maybe i miss some step?
Thank you

Lufti
9 years ago
Reply to  Ayu

You should import the libGoogleAnalyticService.jar into your project path.

john clem
9 years ago
Reply to  Ayu

in android studio, you can drag the .jar to your “libs” folder, then right-click the .jar file and use the “Add As Library” command

Yasir
Yasir
9 years ago

Thanks!!! Everything done perfectly… !! :-D :-D

Very help full….

Damien
9 years ago

Great tutorial, works very well. I looked at the Google documentation but didn’t understand it!

Thanks very much.

Mark
Mark
9 years ago

Thank you much! Worked like a charm.

Bsalbizi
9 years ago

Tried it exactly … but failed … is there anything missing that a beginner should do? And should dash in the analytic code should be removed? u1-434343-fd to ua34434343fd like that… Hopeful.

Tas
Tas
9 years ago

i am trying to implement the above code but the MyApplication class is giving me errors. It is extending class Application but in my source files i dont have an Application class. can someone please help me how i can go about this. Is there any other library that i need to install except the libGoogleAnalyticsServices.jar file ??

PLEASE HELP.

irene
irene
9 years ago

((MyApplication) getApplication()).getTracker(MyApplication.TrackerName.APP_TRACKER);
java.lang.ClassCastException: android.app.Application cannot be cast to com.jappy.flashlight.MyApplication

Tas
Tas
9 years ago
Reply to  irene

IRENE, wat is the correct way to do it then

Tas
Tas
9 years ago

IRENE, what is the correct way to do it then ?

Chaitanya Khurana
Chaitanya Khurana
9 years ago

Hi Ben,

Thank you for nice tutorial.

I thought of integrating Google Analytics primarily to see total installs (including active ones) of my application. When I read your blog, it seems that –
“((MyApplication) getApplication()).getTracker(MyApplication.TrackerName.APP_TRACKER);”
should auto-report app stats and uncaught exception.

So we really don’t need anything else? (Anything beyond what you have provided in your blog)

Also, how can I see total installs of my app on Play Store?

Thanks in advance!

Chaitanya

Back to top button