Sunday, 4 January 2015

Integrating Google Analytics into existing Android app

Analytics are key to measuring the success of your project or application and are a great way of identifying your users trends and demographics. Have you released an app and wondered who your users actually are? Well with analytics you could find out where your users are situated, what ages they are etc. The leader in this field is Google Analytics - this can be embedded into your mobile application, website and even your blog.



After a few frustrating attempts at integrating Google Analytics into an existing app I thought I should post a guide on how to do this.

1. Download the Google play services library and add it to your project.

You can do this by right clicking on the project you want to add analytics to in eclipse, choosing properties and then the Android tab. In the Library section, select Add and choose google-play-services_lib and select Apply.

2. Add the required permissions to AndroidManifest.xml.

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

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

These are required so your app can send the analytics content.

3. Add Metadata to your application. This should be added under the application tab.

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

            android:resource="@xml/global_tracker"/>

We'll add global_tracker later.

4. Create the analytics application helper class.

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

import android.app.Application;

import java.util.HashMap;

public class YourApplication extends Application {

    // The following line should be changed to include the correct property id.
    private static final String PROPERTY_ID = "YOUR_ANALYTICS_ID";

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

    synchronized Tracker getTracker(TrackerName trackerId) {
        if (!mTrackers.containsKey(trackerId)) {

            GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
            analytics.getLogger().setLogLevel(Logger.LogLevel.VERBOSE);
            Tracker t = (trackerId == TrackerName.APP_TRACKER) ? analytics.newTracker(PROPERTY_ID)
                    : (trackerId == TrackerName.GLOBAL_TRACKER) ? analytics.newTracker(
                            R.xml.global_tracker)
                            : analytics.newTracker(R.xml.ecommerce_tracker);
            t.enableAdvertisingIdCollection(true);
            mTrackers.put(trackerId, t);
        }
        return mTrackers.get(trackerId);
    }

}

5. Update AndroidManfiest.xml to include your application, e.g.:

<application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
        android:name=".YourApplication" >

6. Create the tracker xml files. 

Under the res section in your project create an xml folder. Create two xml files in this named ecommerce_tracker.xml and one called global_tracker.xml. Contents below - remember to substitute in your analytics tracking ids. These can be created following instructions here

ecommerce_tracker.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <integer name="ga_sessionTimeout">60</integer>
    <!--  The following value should be replaced with correct property id. -->
    <string name="ga_trackingId">**INSERT TRACKING CODE HERE**</string>
</resources>

global_tracker.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <integer name="ga_sessionTimeout">300</integer>
    <bool name="ga_autoActivityTracking">true</bool>
    <screenName name="**Path to Your Application e.g. com.company.YourApplication**">**YOUR NAME**</screenName>
    <!--  The following value should be replaced with correct property id. -->
    <string name="ga_trackingId">** INSERT TRACKING CODE HERE ** </string>
</resources>

Note the trackers are described as follows by Google 

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.

7. Send the screens

Add the following code to your onCreate method in your activity. This will send the screen views to Google Analytics.

// Get tracker.
Tracker t = ((YourApplication) getApplication()).getTracker(TrackerName.APP_TRACKER);

// Enable Display Features so you can see demographics in Google Analytics
t.enableAdvertisingIdCollection(true);

// Set screen name.
t.setScreenName("** YOUR SCREEN NAME  **");
       
// Send a screen view.
t.send(new HitBuilders.AppViewBuilder().build());

8. Update onStart and onStop

Add the following:

@Override
protected void onStart() {
super.onStart();
GoogleAnalytics.getInstance(this).reportActivityStart(this);
}

@Override
protected void onStop() {
super.onStop();
GoogleAnalytics.getInstance(this).reportActivityStop(this);
}

9. View results in Google Analytics.

You are now done and once users start using your app you should be able to see real time updates in Google Analytics. Note that the analytics aren't exactly real time - but it's good enough! 


Let me know if this helps you out or if you have any further questions and I'll try and help where I can.

EDIT: 11/01/2015 - updated section 7 to allow you to display demographics in Google Analytics.

2 comments:

  1. Look also at this small blog about spyera spy application to know more about spyware market nowadays

    ReplyDelete

Android Studio - How to change app icon (ic_launcher)

Changing your applications icon (ic_launcher) is a common occurrence when developing your android application. Here's quick steps on how...