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
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…
Reference: | Working with Google Analytics API v4 for Android from our JCG partner Ben Wilcock at the Ben Wilcock’s blog blog. |
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.
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
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
You should import the libGoogleAnalyticService.jar into your project path.
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
Thanks!!! Everything done perfectly… !! :-D :-D
Very help full….
Great tutorial, works very well. I looked at the Google documentation but didn’t understand it!
Thanks very much.
Thank you much! Worked like a charm.
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.
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.
((MyApplication) getApplication()).getTracker(MyApplication.TrackerName.APP_TRACKER);
java.lang.ClassCastException: android.app.Application cannot be cast to com.jappy.flashlight.MyApplication
IRENE, wat is the correct way to do it then
here is the answer http://stackoverflow.com/questions/10607392/custom-global-application-class-breaks-with-android-app-application-cannot-be-c
IRENE, what is the correct way to do it then ?
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