3

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.

Regys
  • 79
  • 1
  • 9
  • Sorry I forgot some code where it's clear that GoogleAnalyticsTracker is already meant to be a singleton. Now that is why I ask if just one instance for all app context is enough or if is better to use one for each Activity. Sorry for the misunderstanding. – Regys Jun 14 '11 at 16:34
  • If it's a singleton and an own class already, what do you want to spare then? If you have to many functions to call, see if you can simply group some of them together... – Lukas Knuth Jun 14 '11 at 16:36

2 Answers2

3

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.

Community
  • 1
  • 1
Pedantic
  • 5,032
  • 2
  • 24
  • 37
0

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.

Lukas Knuth
  • 25,449
  • 15
  • 83
  • 111