Jeff Mixon

Just another WordPress site. Literally.

RSS Feed

Google Analytics for Android Quickstart Guide

There’s little doubt that Google Analytics is one of the most powerful analytics tools that exists today and this also applies to Android. I recently implemented GA for the first time on Android and found their Getting Started guide was at once unnecessarily verbose and curiously sparse. I dare say the Advanced Configuration guide is much more useful than the, let’s say, non-advanced(?) variant. But I digress. Here’s the easiest and fastest way to add Google Analytics to your Android app:

Drop these into your AndroidManifest.xml, if necessary:

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

Somewhat ironically, the GA guide recommends extending the Application class while the Application class documentation itself gently discourages this practice. However, this disclaimer is outdated (in my opinion) and extending Application should be chosen over a classical Singleton pattern.

If you haven’t already extended Application, do so now:

...
public class DemoApplication extends Application {
    private Tracker _tracker;
 
    @Override
    public void onCreate() {
        super.onCreate();
 
        GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
 
        if (BuildConfig.DEBUG) {
            analytics.getLogger().setLogLevel(Logger.LogLevel.VERBOSE);
            analytics.setDryRun(true);
        }
 
        _tracker = analytics.newTracker("UA-XXXX-Y");
        // highly recommend using TLS
        _tracker.setUseSecure(true);
 
        ...
    }
 
    public Tracker getTracker() {
        return _tracker;
    }
}

and in your AndroidManifest.xml:

    <application
        android:icon="..."
        android:label="..."
        android:name=".DemoApplication" ...

To use the Tracker:

// Do this somewhere appropriate, such as on onResume() for an activity.
Tracker t = ((DemoApplication) getApplication()).getTracker();
// Set the name of this "screen". This could be the activity,
// fragment, or any logical UI grouping.
t.setScreenName(TAG);
 
// Send a screen view.
t.send(new HitBuilders.AppViewBuilder().build());

That’s it. You don’t need any of that HashMap, enum, xml config nonsense unless you are doing advanced tracking. Hopefully this helps someone else be lazy.

Tags: , , , , , , , .
  • Trackbacks
  • Comments
  • No Comments yet.
  • No trackbacks yet.

Leave a Reply

*