Regys
Regys

Reputation: 79

Google Analytics, what is the best way to use (implement) it from resource/programming perspective?

I am trying to use this feature (Google Analytics) in my app and can't figure out what is the best way to do it.

In first place I began to implement this in each Activity of the application.

public class MyActivity extends Activity {

    public static GoogleAnalyticsTracker tracker;   

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        tracker = GoogleAnalyticsTracker.getInstance();
        tracker.start("UA-YOUR-ACCOUNT-HERE", this);

        tracker.trackPageView("/myActivityView");
    }

    @Override
    public void onDestroy() {
        // Stop the tracker when it is no longer needed.
        tracker.stop();
        super.onDestroy();
    }
}

But now I am thinking it would be better to create just one tracker at Application class and reference it from every Activity instead of repeat this code in each Activity I do create.

Can anyone explain which way is better and why?

Thanks.

Upvotes: 3

Views: 1419

Answers (2)

Pedantic
Pedantic

Reputation: 5022

This: Google Analytics in Android app - dealing with multiple activities

is a good read for coming up with a strategy for using Google Analytics in your Android apps.

In essence, you shouldn't call start()/stop() per activity because start() causes a new visit to be logged which isn't what most people intend or expect. However if this is the behavior you want, you are free to do it that way.

As Lukas said using a singleton or as you said using the Application context to call start()/stop() will get you more accurate tracking, but there are caveats when calling stop() that you need to be aware of. The link above goes into more detail.

Upvotes: 3

Lukas Knuth
Lukas Knuth

Reputation: 25755

Why don't you create a class for your tracker-functions and create and make it a singleton?

This class can then hold all the functions you need (like tracking the page view) and do all the background work for you.

Upvotes: 0

Related Questions