20. Enabling Application Statistics with Google Analytics

Most Android developers want to know what their users are up to. How long do users spend in the application? How often do they use it? What features of the application are they using and not using? Is the user interface designed so that users can find what they need? What sorts of devices are users using? In this chapter, we discuss how application developers can use the Google Analytics SDK for Android to collect and track information about their application users in a consistent, robust fashion.


Image Tip

Many of the code examples provided in this chapter are taken from the SimpleStats application. The source code for this application is provided for download on the book’s website.


Creating a Google Account for Analytics

To send data to the Google Analytics service and later access the statistics your application gathers on the Google Analytics Dashboard, you need to create a developer account at http://www.google.com/analytics. Much like your Google Play account, your Google Analytics account must be tied to an underlying Google account. The accounts are free to start. Figure 20.1 shows the Google Analytics signup page for a registered Google account.

Image

Figure 20.1 The Google Analytics signup page.


Image Note

The account setup is primarily targeted at website statistics tracking, but mobile developers use the same workflow, so don’t get confused and think you’re in the wrong place.


As part of the account creation, you’ll be asked to log in with your Google account credentials. Then you’ll be prompted to enter some information to set up your account. When you are prompted to enter a website or mobile app for tracking purposes, choose the mobile app option and enter an Account Name (ideally including the name of your app and company domain, such as http://simplestats.advancedandroidbook.com) and an App Name such as SimpleStats. You also need to set the Industry Category and the Reporting Time Zone to which you want to normalize statistics. Next, you enter sharing options for the account. Finally, you need to press Get Tracking ID and accept the Google Analytics Terms of Service.


Image Tip

For the same reason as for Google Play, it’s recommended that you create your Google Analytics account with a generic Google account, such as one for a company entity, as opposed to an individual’s account, so you’re not trying to track down a specific person’s login information on a weekend or some other inconvenient time. It’s just more professional that way. You can add other people to the account with the Analytics account settings, too.


The resulting account creation generates a Tracking ID for your application to use with your SDK. The Tracking ID is displayed within the Google Analytics Admin console preceded by the letters “UA-” followed by some numbers (as shown in Figure 20.2). Save this information—you will need to use this number in your application to send statistics to the proper Google Analytics account. You can create different accounts with different tracking identifiers from your Google Analytics account, or use the same one for all your apps. It depends on what you want out of the reports.

Image

Figure 20.2 The Google Analytics Admin section.

When you navigate to the Reporting section, you may be greeted with an empty Dashboard when you first log in to your account, as shown in Figure 20.3.

Image

Figure 20.3 The Google Analytics Reporting section.

Adding the Library to Your Android IDE Project

Now you’re ready to work with the Google Analytics SDK for Android. This library is available via the Android SDK Manager by installing the Google Play services library. When installed, the Google Play services library is located in the SDK directory under <path_to_sdk>/extras/google/google_play_services/libproject/google-play-services_lib.


Image Note

At the time of this writing, we used the Google Analytics SDK for Android version 4.


To use the Google Analytics SDK for Android, you must first import the google-play-services_lib project into your Android IDE as a library project. To integrate the SDK into your Android IDE project, follow these steps:

1. Add the google-play-services_lib to your project.

2. Add two permissions to your Android manifest file.

3. Add the Google Play services library as a dependency to the <application> element in the Android manifest file.

Adding the google-play-services_lib to your project in the Android IDE is easy:

1. Right-click the application to which you would like to add Analytics support and choose Properties.

2. Under the Android settings, select the Add . . . button under the Library heading.

3. Choose the google-play-services_lib project and select OK, then select OK again.

Because you are sending information over the network, you need to add two permissions to your application. To do this, follow these steps:

1. Click the Permissions tab of the Android manifest file for your application.

2. Add the permission called android.permission.INTERNET.

3. Add the permission called android.permission.ACCESS_NETWORK_STATE.

4. Save your Android manifest file.

You also must add the Google Play services library as a dependency to your Android manifest file. To do this, follow these steps:

1. Add the following line of code as a child element within the <application> element of the manifest file:

Click here to view code image

<meta-data android:name="com.google.android.gms.version"
           android:value="@integer/google_play_services_version" />

2. Save your Android manifest file.

You can now start using the classes in the Google Analytics SDK for Android.


Image Tip

You may also need to create a Proguard Exception to your application to prevent ProGuard from removing classes that are required during compilation. To learn more about what lines you should include, see the following: http://d.android.com/google/play-services/setup.html#Proguard.


Collecting Data from Your Applications

Now that you’ve created an account and added the Google Play services library to your project, you’re ready to start using Google Analytics to track events and other information in your application. To start tracking in an Activity class, retrieve an instance of GoogleAnalytics. You typically want to start tracking in the onCreate() method of your Activity, track various events throughout your Activity lifecycle, and stop tracking in your onDestroy() method. To start tracking, supply your UA- account number and an interval (seconds) at which to dispatch events to the server, such as this:

GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
mTracker = analytics.newTracker("UA-1234567-89");
analytics.reportActivityStart(this);

When you’re done tracking, stop the tracker:

analytics.reportActivityStop(this);

Stopping a tracking session is commonly performed in the onDestroy() callback method of your Activity class.

Logging Different Events

Now that you’ve got the SDK set up and working with your application, you want to look into the different types of events you can log with the Google Analytics SDK for Android. You can log page views, events, e-commerce events, and other useful information. The logging methods are flexible enough that you can adapt them to your needs.

During a valid tracking session, you can track events by supplying the category, action, label, and value (all developer-defined fields) of an event like so:

buttonEvent = new EventBuilder();
buttonEvent.setCategory("Click");
buttonEvent.setAction("Press");
buttonEvent.setLabel("Button");
buttonEvent.setValue(0);
mTracker.send(buttonEvent.build());

Using the Google Analytics Dashboard

After users begin to use your application, the statistics are collected for each of the event hooks you have put in place in your application. This data is then sent to the Google Analytics servers, and it’s time to head over to the Google Analytics Dashboard and interpret the results.


Image Tip

Luckily, some of the statistics collected by Google Analytics are now shown in real time. Earlier versions had up to a 24-hour delay between when an event was logged and when it showed up in the data on the Dashboard. Real-time statistics are still in beta at the time of this writing.


When your data has been collected and run through the Google Analytics servers, your Dashboard should show the data on the Home screen overview, as shown in Figure 20.4.

Image

Figure 20.4 The Google Analytics Dashboard.

You can review the Users Overview details by clicking on the Reporting tab and choosing Audience, Overview, as shown in Figure 20.5.

Image

Figure 20.5 A Google Analytics Users Overview report.

You can drill down to the individual button click events by clicking on the Reporting tab and choosing Behavior, Events, Overview, and then drilling down by clicking on the Top Events, Event Label link. This displays the button click events, as shown in Figure 20.6.

Image

Figure 20.6 A Google Analytics Event Overview report.

The Google Analytics Dashboard has a variety of useful features. We recommend reading through the documentation and messing around with where you put your event hooks in the application prior to publication, as you may want to adjust your analysis strategy to get the reports you desire.

Gathering E-commerce Information

You can also use the Google Analytics SDK for Android to track e-commerce data. This data includes store transactions, purchase data, and other useful information for e-commerce services, which can just as easily include tracking in-app billing data or virtual purchases in a game.


Image Note

This type of tracking is not enabled by default. You need to log in to your Google Analytics Dashboard and enable e-commerce tracking under the profile settings of your specific account.


Logging E-commerce Events in Your Applications

To start tracking e-commerce information, you must still instantiate the tracker as with other types of events. Then, when you are processing in-app payments or the like, you can use the TransactionBuilder class to log information about a user purchase. Basically, think of a TransactionBuilder as a shopping cart instance; the ItemBuilder class is used to specify the individual items purchased in the cart. Here is the sample code necessary to build a transaction with two items for purchase:

String orderID = "1001" + new Date().toString();

transactionEvent = new TransactionBuilder();
transactionEvent.setTransactionId(orderID);
transactionEvent.setAffiliation("My Game Store");
transactionEvent.setShipping(0);
transactionEvent.setRevenue(2.99);
transactionEvent.setTax(0);
transactionEvent.setCurrencyCode("USD");

mTracker.send(transactionEvent.build());

Both the Transaction and Item classes have helper Builder classes:

// Item #1
item1Event = new ItemBuilder();

item1Event.setTransactionId(orderID);
item1Event.setName("1 Game Credit");
item1Event.setSku("SKU_123");
item1Event.setPrice(1.99);
item1Event.setQuantity(1);
item1Event.setCategory("LIFE POINTS");
item1Event.setCurrencyCode("USD");

mTracker.send(item1Event.build());

// Item #2
item2Event = new ItemBuilder();

item2Event.setTransactionId(orderID);
item2Event.setName("1 Game Credit");
item2Event.setSku("SKU_456");
item2Event.setPrice(0.99);
item2Event.setQuantity(1);
item2Event.setCategory("Game Credit");
item2Event.setCurrencyCode("USD");

mTracker.send(item2Event.build());

When you’re ready to commit the event and dispatch the results to the Google Analytics servers, simply use the send() method of the Tracker class, including the parameters of the event that you are tracking:

mTracker.send(eventToTrack.build());

Reviewing E-commerce Reports

After you have logged some e-commerce events, you can check out the reports on the Google Analytics Dashboard (assuming you enabled e-commerce tracking in your profile). You can find these reports on the Reporting tab, under the Conversions, Ecommerce section. Figure 20.7 shows an Ecommerce Overview report after multiple clicks of the Buy button in the sample application running the TransactionBuilder code shown earlier.

Image

Figure 20.7 A Google Analytics Ecommerce Overview report.

Tracking Ad and Market Referrals

The SDK supports several types of campaign tracking, which allow you to keep track of installation referrals through the Android Market and otherwise. To participate in Google Play campaign tracking, see the online documentation: https://developers.google.com/analytics/devguides/collection/android/v4/campaigns.

Gathering Statistics

Now let’s talk about some strategies, as well as tips and tricks, for gathering relevant, useful statistics with Google Analytics. Much of the “magic” involves dropping statistics-gathering hooks at clever places in your specific applications. The trick is to place your event hooks at exactly the places in your application that mean something to you, the developer. Place the hooks in the wrong code locations, and you’re going to generate erroneous statistics. It’s a bit of an art to do this well, and it’s not really something we can give you examples for, but we can talk about some commonsense approaches. For example:

Image Develop, document, and test your event-tracking strategy and make it consistent. When you track events, you can provide a category, action, label, and value. Use these features consistently throughout your application so that the creation of reports is done in a similar fashion, regardless of who added the event hooks in that part of the application. We see a lot of tracking solutions that generate tons of data but little of real value.

Image Know all your application entry points. Most users will launch your application from the application tray, but you might have other entry points as well, via notifications or live folders and other intents. If you’re trying to log application launches, you need to log each entry point to get an accurate result.

Image Remember your application, Activity, and Fragment lifecycle events. You might want to log each time an Activity or Fragment runs. Make sure you do this in a callback that runs only once per Activity or Fragment, such as the onCreate() callback. You probably want to avoid logging onResume(), as it may be called repeatedly during the lifetime of an Activity or Fragment. Even so, keep in mind that something as simple as rotating the screen will result in a new call to onCreate().

Image Gather only the statistics you need, and don’t store them if you can avoid it. Gathering excessive information from the user creates and exacerbates a number of issues regarding performance and privacy.

Image Consider tracking behavior rather than page views. For example, you can rank the difficulty of a game by tracking the actions of restarting, dying, quitting frequently, opening help or forum links, and so on. Higher frequencies of these compared to a “completion” action might indicate a higher level of difficulty. In a newsreader application, tracking views that last longer than 30 seconds or involve scrolling down to more content might be more useful than just tracking the number of times an article is loaded. In fact, behavior is often what analytics tries to glean from page views. You’re writing a full application and can more directly indicate behavior through careful creation of tracking events.

Image Always verify your assumptions that any data you use is unique. Timestamps are not globally unique. Handset device identifiers are available on smartphones, but not tablets and other types of devices.

Protecting Users’ Privacy

When you collect user statistics, you need to make sure that the users are aware of your activities, so that privacy concerns are addressed. The Google Analytics Terms of Service require that you indicate to your application users that you reserve the right to anonymously track and report a user’s activity inside of your application. By signing up for a Google Analytics account, you agree to these terms. Send only anonymous information that can be aggregated to the Google Analytics servers. Do not send private user information. This isn’t the only item you must comply with in the terms of service, of course. Be sure to read and understand them before adding instrumentation to your code with many calls.

Summary

The Google Analytics SDK for Android is an effective way to generate helpful information about how users are using your applications. It’s flexible, powerful, and easy to integrate into your applications. As with any logging, you should always inform your users that you are tracking their behavior in the application and have a well-understood privacy policy. How you take advantage of the Google Analytics SDK for Android depends on what you’re hoping to determine from your users. Heavy analytics may be appropriate for beta projects, whereas lightweight informational logging might be more appropriate for published applications.

Quiz Questions

1. True or false: To track your application, you must use the Analytics ID created during the Google Analytics application setup process.

2. What letters are used at the beginning of the tracking ID of a Google Analytics application?

3. What library project must you include in your application to leverage the Google Analytics version 4 SDK for Android?

4. What two android.permission values are required to use the Google Analytics SDK for Android?

5. True or false: The commit() method of the Tracker class is used to submit events to the Google Analytics servers.

Exercises

1. Use the Google Analytics SDK for Android documentation to determine how you would send social interactions to Google Analytics.

2. Use the Google Analytics SDK for Android documentation to determine how you would perform automatic session management.

3. Create an application that is capable of sending a screen view to Google Analytics.

References and More Information

Google Analytics documentation:

http://code.google.com/apis/analytics/

Google Analytics account signup (requires a Google account):

http://www.google.com/analytics/sign_up.html

Google Analytics documentation for event tracking:

https://developers.google.com/analytics/devguides/collection/android/v4/events

Google Analytics documentation for e-commerce tracking:

https://developers.google.com/analytics/devguides/collection/android/v4/ecommerce

Google Analytics documentation on tracking campaigns:

https://developers.google.com/analytics/devguides/collection/android/v4/campaigns

“Best Practices for Mobile App Analytics Setup”:

https://support.google.com/analytics/answer/2587087

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.7.174