Android 应用程序中的 Google Analytics - 处理多项活动 [英] Google Analytics in Android app - dealing with multiple activities

查看:13
本文介绍了Android 应用程序中的 Google Analytics - 处理多项活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看到在我的应用中设置 Google Analytics 是多么容易,我感到非常兴奋,但是文档的缺乏让我有一些问题.我能找到的唯一信息来自文档这里,它仅着眼于从一个活动报告页面浏览量和事件.我想在我的应用中报告多个活动的页面浏览量和事件.

I was pretty excited to see how easy it is to set up Google Analytics with my app, but the lack of documentation has me sitting with a few questions. The only information that I can find is right from the documentation here, which only looks at reporting PageViews and Events from one Activity. I want to report PageViews and Events across multiple Activities in my app.

现在在我所有活动的 onCreate() 中,我正在调用:

Right now in the onCreate() of all of my activities, I am calling:

    tracker = GoogleAnalyticsTracker.getInstance();
    tracker.start("UA-xxxxxxxxx", this);

在我所有活动的 onDestroy() 中:

And in the onDestroy() of all of my activities:

    tracker.stop();

然后我根据需要跟踪页面视图和事件,并将它们与我正在执行的另一个 HTTP 请求一起分派.但我不确定这是最好的方法.我应该在每个活动中调用 start() 和 stop(),还是应该只在主启动器活动中调用 start() 和 stop()?

I then track PageViews and Events as needed, and Dispatch them along with another HTTP request I am performing. But I'm not so sure this is the best way. Should I be calling start() and stop() in each activity, or should I only call start() and stop() in my main launcher activity?

推荐答案

在每个活动中调用 start()/stop() 的问题(正如 Christian 所建议的)是它导致每个活动的新访问"您的用户导航到.如果这适合您的使用,那很好,但是,这不是大多数人期望访问工作的方式.例如,这会使将 android 号码与网络或 iphone 号码进行比较变得非常困难,因为网络和 iphone 上的访问"映射到会话,而不是页面/活动.

The problem with calling start()/stop() in every activity (as suggested by Christian) is that it results in a new "visit" for every activity your user navigates to. If this is okay for your usage, then that's fine, however, it's not the way most people expect visits to work. For example, this would make comparing android numbers to web or iphone numbers very difficult, since a "visit" on the web and iphone maps to a session, not a page/activity.

在您的应用程序中调用 start()/stop() 的问题在于它会导致意外的长时间访问,因为 Android 不保证在您的最后一个活动关闭后终止应用程序.此外,如果您的应用对通知或服务执行任何操作,这些后台任务可能会启动您的应用并导致幻影"访问.更新:stefano 正确地指出 onTerminate() 永远不会在真实设备上调用,因此没有明显的地方可以调用 stop().

The problem with calling start()/stop() in your Application is that it results in unexpectedly long visits, since Android makes no guarantees to terminate the application after your last activity closes. In addition, if your app does anything with notifications or services, these background tasks can start up your app and result in "phantom" visits. UPDATE: stefano properly points out that onTerminate() is never called on a real device, so there's no obvious place to put the call to stop().

在单个主"活动中调用 start()/stop() 的问题(如 Aurora 所建议的)是无法保证活动会在您的用户使用您的应用程序期间一直存在.如果主要"活动被销毁(比如释放内存),您随后在其他活动中将事件写入 GA 的尝试将失败,因为会话已停止.

The problem with calling start()/stop() in a single "main" activity (as suggested by Aurora) is that there's no guarantee that the activity will stick around for the duration that your user is using your app. If the "main" activity is destroyed (say to free up memory), your subsequent attempts to write events to GA in other activities will fail because the session has been stopped.

此外,至少在 1.2 版之前,Google Analytics 中存在一个错误,导致它保留对传递给 start() 的上下文的强引用,防止它在销毁后被垃圾收集.根据上下文的大小,这可能是一个相当大的内存泄漏.

In addition, there's a bug in Google Analytics up through at least version 1.2 that causes it to keep a strong reference to the context you pass in to start(), preventing it from ever getting garbage collected after its destroyed. Depending on the size of your context, this can be a sizable memory leak.

内存泄漏很容易修复,可以通过使用应用程序而不是活动实例本身调用 start() 来解决.docs 可能应该更新以反映这一点.

The memory leak is easy enough to fix, it can be solved by calling start() using the Application instead of the activity instance itself. The docs should probably be updated to reflect this.

例如.从您的活动内部:

eg. from inside your Activity:

// Start the tracker in manual dispatch mode...
tracker.start("UA-YOUR-ACCOUNT-HERE", getApplication() );

代替

// Start the tracker in manual dispatch mode...
tracker.start("UA-YOUR-ACCOUNT-HERE", this ); // BAD

关于何时调用 start()/stop(),您可以实现一种手动引用计数,为每次调用 Activity.onCreate() 增加一个计数,并为每个 onDestroy() 减少一个计数,然后调用 GoogleAnalyticsTracker.stop() 当计数达到零时.

Regarding when to call start()/stop(), you can implement a sort of manual reference counting, incrementing a count for each call to Activity.onCreate() and decrementing for each onDestroy(), then calling GoogleAnalyticsTracker.stop() when the count reaches zero.

来自 Google 的新 EasyTracker 库将采用为你照顾这个.

The new EasyTracker library from Google will take care of this for you.

或者,如果您不能子类化 EasyTracker 活动,您可以在自己的活动基类中自己手动实现:

Alternately, if you can't subclass the EasyTracker activities, you can implement this manually yourself in your own activity base class:

public abstract class GoogleAnalyticsActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Need to do this for every activity that uses google analytics
        GoogleAnalyticsSessionManager.getInstance(getApplication()).incrementActivityCount();
    }

    @Override
    protected void onResume() {
        super.onResume();

        // Example of how to track a pageview event
        GoogleAnalyticsTracker.getInstance().trackPageView(getClass().getSimpleName());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        // Purge analytics so they don't hold references to this activity
        GoogleAnalyticsTracker.getInstance().dispatch();

        // Need to do this for every activity that uses google analytics
        GoogleAnalyticsSessionManager.getInstance().decrementActivityCount();
    }

}



public class GoogleAnalyticsSessionManager {
    protected static GoogleAnalyticsSessionManager INSTANCE;

    protected int activityCount = 0;
    protected Integer dispatchIntervalSecs;
    protected String apiKey;
    protected Context context;

    /**
     * NOTE: you should use your Application context, not your Activity context, in order to avoid memory leaks.
     */
    protected GoogleAnalyticsSessionManager( String apiKey, Application context ) {
        this.apiKey = apiKey;
        this.context = context;
    }

    /**
     * NOTE: you should use your Application context, not your Activity context, in order to avoid memory leaks.
     */
    protected GoogleAnalyticsSessionManager( String apiKey, int dispatchIntervalSecs, Application context ) {
        this.apiKey = apiKey;
        this.dispatchIntervalSecs = dispatchIntervalSecs;
        this.context = context;
    }

    /**
     * This should be called once in onCreate() for each of your activities that use GoogleAnalytics.
     * These methods are not synchronized and don't generally need to be, so if you want to do anything
     * unusual you should synchronize them yourself.
     */
    public void incrementActivityCount() {
        if( activityCount==0 )
            if( dispatchIntervalSecs==null )
                GoogleAnalyticsTracker.getInstance().start(apiKey,context);
            else
                GoogleAnalyticsTracker.getInstance().start(apiKey,dispatchIntervalSecs,context);

        ++activityCount;
    }


    /**
     * This should be called once in onDestrkg() for each of your activities that use GoogleAnalytics.
     * These methods are not synchronized and don't generally need to be, so if you want to do anything
     * unusual you should synchronize them yourself.
     */
    public void decrementActivityCount() {
        activityCount = Math.max(activityCount-1, 0);

        if( activityCount==0 )
            GoogleAnalyticsTracker.getInstance().stop();
    }


    /**
     * Get or create an instance of GoogleAnalyticsSessionManager
     */
    public static GoogleAnalyticsSessionManager getInstance( Application application ) {
        if( INSTANCE == null )
            INSTANCE = new GoogleAnalyticsSessionManager( ... ,application);
        return INSTANCE;
    }

    /**
     * Only call this if you're sure an instance has been previously created using #getInstance(Application)
     */
    public static GoogleAnalyticsSessionManager getInstance() {
        return INSTANCE;
    }
}

这篇关于Android 应用程序中的 Google Analytics - 处理多项活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆