Wednesday, May 28, 2014

Busy developer Android Google Analytics guide

I was working on integrating Google Analytics (GA) into existing Android application. If you want to track your activities in GA, you need to put stop and start reports in your activities onStart and onStop lifecycle events. You need to do this in _every_ activity.

I don't like this approach, it doesn't feel right (I hate copy paste code in any form).

Luckily there is another approach.

You can implement ActivityLifecycleCallbacks and then you can override onActivityStopped and onActivityStarted methods and by doing so, you will put start and stop method in every activity. Here is how to do it:

public class CustomActivityLifeCycleListener implements Application.ActivityLifecycleCallbacks {

    @Override
    public void onActivityStopped(Activity activity) {
        GoogleAnalytics.getInstance(activity).reportActivityStop(activity);
    }

    @Override
    public void onActivityStarted(Activity activity) {
        GoogleAnalytics.getInstance(activity).reportActivityStart(activity);
    }

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {

    }

    @Override
    public void onActivityResumed(Activity activity) {

    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {

    }

}
You need to register this LifeCycle listener in you application class (by extending Application) and initialize your GA tracker.
public class App extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        registerActivityLifecycleCallbacks(new CustomActivityLifeCycleListener());
        //R.xml.global_tracker is my tracker configuration, you can also initialize tracker
        //by passing your GA property in String constructor.
        GoogleAnalytics.getInstance(getContext()).newTracker(R.xml.global_tracker);
    }

}
You can also save this tracker (instance) in your app class because you will need tracker if you want to send events or whatever.

One more thing. You need to register your tracker resource in your AndroidManifest or else your GA configuration will not work. It took me something like 3h until I figure this out!

Also you need to update yours Google Play Service lib and install Google Analytics libs in your Android SDK tool.

No comments:

Post a Comment