Google Analytics - Android Development Patterns: Best Practices for Professional Developers (2016)

Android Development Patterns: Best Practices for Professional Developers (2016)

Chapter 17. Google Analytics

As the mobile device market gains more developers, the need to analyze and formulate a plan for a successful app is more important than ever. Previously, testing and tuning an app relied heavily on direct user feedback, focus groups, and user reviews. As part of your developer tool belt, you can integrate Google Analytics and find out where your app falls down and where users are struggling.

Adding Google Analytics

Google Analytics is a service provided by Google that works on multiple platforms. Web developers use Google Analytics to monitor the visits and purchases made by users. Now mobile developers using Android or iOS can take advantage of Google Analytics in their apps.

Before we get too far into the process, you first need to enable Google Services for the app. This can be done by visiting https://developers.google.com/mobile/add and using the wizard to generate your configuration file.

If you have not already added your app to the Google Developer Console, you can use this wizard to create a new app and specify the Android package name for your app. While using the wizard, you will also be asked to choose or create a new analytics account to track and report data. When you are finished either choosing an account or creating one, make sure to generate your configuration file. This will download a file named google-services.json to your computer.

When the file has been generated and downloaded, you need to move or copy it into the app folder of your Android project. Because your installation of Android Studio and your project directory may vary, you need to locate the /app folder and place the google-services.json file in it.

Once you copy your configuration file, you need to make an edit to the top-level build.gradle file of your project. You need to add the following dependency:

classpath 'com.google.gms:google-services:1.4.0-beta3'

Note that this version is current as of this writing, and you need to update to the latest version to take advantage of any new features and functionality. You also need to make some additions to your app module build.gradle file, which consists of adding the following lines:

// other plugins
apply plugin: 'com.google.gms.google-services'

dependencies {
// other dependencies
compile 'com.google.android.gms:play-services-analytics:8.1.0'
}

Now that you have the build configured, you need to make some changes to your AndroidManifest.xml file. Because Google Analytics is an online service and you will be sending data, you need to add the INTERNET and ACCESS_NETWORK_STATE permissions to yourAndroidManifest.xml file. The following shows a snippet of the required entries:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.analytics">

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

<application android:name="AnalyticsApplication">

<!-- The rest of your application manifest -->

</application>
</manifest>
With the configuration in place, Google recommends that you subclass Application to
set up your tracking information. The following code snippet shows the code that
Google recommends implementing:/*
* Copyright Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.google.samples.quickstart.analytics;

import android.app.Application;

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

/**
* This is a subclass of {@link Application} used to provide shared objects for
* this app, such as the {@link Tracker}.
*/
public class AnalyticsApplication extends Application {
private Tracker mTracker;

/**
* Gets the default {@link Tracker} for this {@link Application}.
* @return tracker
*/
synchronized public Tracker getDefaultTracker() {
if (mTracker == null) {
GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
// To enable debug logging use: adb shell setprop log.tag.GAv4 DEBUG
mTracker = analytics.newTracker(R.xml.global_tracker);
}
return mTracker;
}
}

You can now get an instance of the tracker and start tracking inside of an Activity by adding the following code to the appropriate methods:

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

// set up the shared Tracker
AnalyticsApplication application = (AnalyticsApplication) getApplication();
mTracker = application.getDefaultTracker();
}

@Override
public void onResume() {
super.onResume(); // Always call the superclass method first

// add log to make sure that GA is being called...
Log.i(TAG, "Setting screen name: " + name);
mTracker.setScreenName("Image~" + name);
// send the "hit" to GA
mTracker.send(new HitBuilders.ScreenViewBuilder().build());
}

Note that instead of using the onResume() method, you could use another Activity or ViewPager. For any View, Fragment, or Activity for which you want tracking information, you need to add the tracking code as well as send the Hit by using the HitBuilders class.

You can find a demo application on GitHub that shows a slightly different configuration but is a great starting point for your Android project for adding Google Analytics to your app. It can be found at https://github.com/googleanalytics/hello-world-android-app.

Google Analytics Basics

Web developers have enjoyed the Google Analytics service for several years. It enables them to set up marketing campaigns, test different versions of web pages, and, most importantly, find where the gaps are in their online offerings.

As an app developer, the prospect of being able to determine where users are struggling and even see the amount of time they spend on a view inside of your application can help you to create and fine-tune an application that will be used more and shared with others.

By default, Google Analytics provides the following information when integrated into an app:

Image User and session count

Image Session duration

Image Operating system information

Image Device model

Image Geographic location

In addition to the included statistics, you can use and create the following to enhance your app analytics:

Image Events

Image Goals

Image Ecommerce

Image Custom timings

Image Custom dimensions

Image Custom metrics

Each of these additional features gives you greater insight into your application and can work together to help you get the most out of your app. Let’s take a closer look at what each of these features is and how it would be used.

Events

An event is an action or objective that a user performs that can be quantified. For example, you can create an event that will track how many times a user taps the Help button, or even how many views the Support section of your app is getting.

Events are made up from four components:

Image Category

Image Action

Image Label (optional)

Image Value (optional)

The category is a custom name or organizational group you can add to your actions. Because you may want to track more than one action, you may find that grouping actions together will help you process the return data. It is important that you plan for how you will be reporting data before you decide on a concrete category name. If you were to use a generic category, such as Visits or Views, you may end up with a lot of information that really isn’t quantifiable for a particular page. Instead, “Visit – Help” and “View – High Score” would be better category names if you are wanting to capture those specific events. If your app happens to be a game, you could consider using the level the player is on as the category name.

The action is separate from the category, but is still part of the event. You can name an action based on what a user is doing, or what task they have initiated or completed. For example, you could name an action “abandonment,” “paused,” or “saving.” Note that because actions are separate from categories, you can use the same named action inside of two different event calls with different categories. This flexibility allows you to have an action that happens in two different categories and also gives you the ability to have unique actions that only happen in one category.

A label is an optional component that is used for additional information you want tracked with the category and action. This label could be used to pass system information, download information, or even create a note on why the event was triggered.

Value is also an optional component, and unlike the other components it’s a positive integer value. This value can be tied to just about any integer value you want. For example, you could use it as a counter value, a time-to-render value, or even a value to track how long a user has been on a certain screen, view, or level.

The following code snippet demonstrates tracking an event in a game:

// Event to track coin gathering
mTracker.send(new HitBuilders.EventBuilder()
.setCategory("Brackety Bricks")
.setAction("Collect")
.setLabel("coin")
.setValue(1)
.build());

Goals

Goals determine if objectives are being met in your app. The objectives are defined by you and may consist of page visits, purchases, or even collecting user information. Goals are closely tied to conversion, which is the term for a completion of a goal or objective.

Goals can fall into one of the following types:

Image Destination: A user has loaded or visited a specific location.

Image Duration: A user has spent a minimum amount of time in a session.

Image Pages/Screens per session: A user has visited or viewed a specific number of pages or screens.

Image Event: A specific event was triggered.

Goals also work with funnels for tracking how users reach goals. Funnels show you the shape of user traffic and flow through a site or app. At the beginning, all users start at the top of the funnel and then they filter out as they fail to achieve a particular goal or objective. This leaves you with a smaller sample and gives not only a “funnel” shape to your report, but also shows how the traffic is funneled, through conversion to goal completion.

For more information on how to work with custom funnels in Google Analytics, visit https://support.google.com/analytics/answer/6180923?hl=en.

When you are working with an ecommerce or monetary goal, you can assign a dollar amount. This can be helpful when making forecasts or when working on a commerce plan. The generated reports take the amount you assign per goal and give you an estimate on whether you are on track to meet your financial goals or if you need to adjust your app or objectives.

Think carefully about how to want to create goals, because you are only allotted 20 goals in total. You can create goal sets of five goals each if the goals you have created are related to each other. Once you create a goal, you cannot delete it. You can, however, repurpose it. Keep in mind that because you are modifying an existing goal, it may make the reports you run confusing because it will appear that the “new” goal existed in the past and with numbers that may not make sense in the “new” context.

Ecommerce

Enhanced ecommerce allows you to track impressions, promotions, checkout process, refunds, transactions, and other purchase-related activities. Ecommerce works closely with goals and events, because to report ecommerce data you must send it with an existing hit.

To track a product purchase made in your application, you must first create a product and assign a name and price to it. You can then set up a ProductAction and assign a transaction ID. Following that, you build the tracking event and send it to Google Analytics. The following code snippet demonstrates this:

// create the Product
Product product = new Product()
.setName("Rocket Fuel")
.setPrice(10.00);

// set the ProductAction
ProductAction productAction = new ProductAction(ProductAction.ACTION_PURCHASE)
.setTransactionId("T01701");

// add the transaction to an Event
HitBuilders.EventBuilder builder = new HitBuilders.EventBuilder()
.setCategory("In-Game Store")
.setAction("Purchase")
.addProduct(product)
.setProductAction(productAction);

// send the transaction data with the event
mTracker.send(builder.build());

Custom Timings

A custom timing is used when you want to measure the length of time it takes to complete a particular task in your app. Custom timings are similar to events in that they are created in almost the same manner; however, custom timings are different in that they are time based.

The following snippet shows an example of how to create a custom timing for how long it takes a user to complete a task in a game:

// build and send a custom timing
mTracker.send(new HitBuilders.TimingBuilder()
.setCategory("Brackety Bricks")
.setValue(42000) // 42 seconds
.setVariable("First Stage")
.setLabel("Race")
.build());

Similar to setting up an event, you use a category, value, and label. The difference is that instead of an action, a variable is used instead. The integer value component is used to send timing information.

Custom Dimensions

Custom dimensions allow you to create reports that track users with a particular trait, attribute, or matching metadata set. This can be useful for determining a player’s skill level, the difficulty level the majority of players select, or even the type of device most players are using to play your game.

Setting up a custom dimension requires some setup inside of the Google Analytics web interface. Note that similar to working with goals, you only have 20 available slots for setting up custom dimensions.

The following is a snippet used to add data that shows the currently selected skill level for the level Brackety Bricks:

// set a custom dimension to track level and difficulty
mTracker.setScreen("BracketyBricks");
mTracker.send(new HitBuilders.ScreenViewBuilder()
.setCustomDimension(3, "Brackety Bricks")
.build()
);

Custom Metrics

Custom metrics are similar to custom dimensions, in that they are allowed to use different scopes. A custom metric is best used when you need to create a report that covers data that may be difficult to track elsewhere without creating excess and erroneous data.

Creating a custom metric is done inside of the Admin settings, under the Property section and as an option listed in Custom Definitions of the Google Analytics web interface. A custom metric requires the following:

Image A name

Image A scope set to either Hit or Product

Image A formatting type of Integer, Currency, or Time

Optionally, you can opt to set up a minimum value as well as a maximum value for your custom metric.

The following snippet shows reporting a view to a hint screen during a level of Brackety Bricks as a custom metric:

mTracker.setScreen("BracketyBricks");
mTracker.send(new HitBuilders.ScreenViewBuilder()
.setCustomMetric(1, "Hint Page")
.build()
);

Summary

In this chapter, you learned how to add Google Analytics to your Android project. You learned about the features of Google Analytics that you can use to gain a greater understanding of your application and how users are using your app.

You learned about tracking user interaction through events. You were shown how to create events to track specific tasks or objectives in your app.

You also learned about goals and how they work with events and ecommerce tracking to create funnel reports. You learned that the funnel is important because it allows you to fine-tune your app to meet the needs of your users and increase your revenue stream. You also learned that you are limited to having 20 goals that can be reused but not deleted.

You learned about ecommerce tracking and how data is sent with other events. You learned that ecommerce is used with creating products and tracking the transaction and sale of products.

You also learned about using custom timings with Google Analytics. Custom timings are similar to events; however, the value passed is used to track how long a user takes to complete an objective rather than be used as a counter or other numeric value.

You then learned about custom dimensions. Custom dimensions require extra setup, but allow you to track custom values such as the skill or difficulty setting selected for a particular level. Similarly to goals, you are limited to having 20 custom dimensions in total, but they can be reused when needed.

Finally, you learned about custom metrics, which are similar to custom dimensions in reporting useful data back to you. You learned the requirements for using a custom metric as well as how to implement the code for reporting the metric back to Google Analytics.