Working with Google Analytics API v4 for Android
Join the DZone community and get the full member experience.
Join For Freefor 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); } }
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.
04-11 13:25:05.026 13287-13304/com.mycompany.myapp v/gav3? thread[gathread,5,main]: connecting to analytics service 04-11 13:25:05.030 13287-13304/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) } 04-11 13:25:05.030 13287-13304/com.mycompany.myapp w/gav3? thread[gathread,5,main]: service unavailable (code=1), will retry. 04-11 13:25:05.043 13287-13304/com.mycompany.myapp v/gav3? thread[gathread,5,main]: loaded clientid 04-11 13:25:05.045 13287-13304/com.mycompany.myapp i/gav3? thread[gathread,5,main]: no campaign data found. 04-11 13:25:05.045 13287-13304/com.mycompany.myapp v/gav3? thread[gathread,5,main]: initialized ga thread 04-11 13:25:05.067 13287-13304/com.mycompany.myapp v/gav3? thread[gathread,5,main]: puthit called ... 04-11 13:25:10.106 13287-13304/com.mycompany.myapp v/gav3? thread[gathread,5,main]: dispatch running... 04-11 13:25:10.623 13287-13304/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…
about the author
ben wilcock is an freelance consultant specialising in soa, cloud and mobile applications. you can read his blog at http://benwilcock.wordpress.com/ or contact him via twitter (@benbravo73) or via his company website at http://www.soagrowers.com/ . he’s also author of trip computer , the low power distance tracking app for android.
Published at DZone with permission of Ben Wilcock, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments