谷歌Analytics(分析)的Andr​​oid应用 - 处理多个活动 [英] Google Analytics in Android app - dealing with multiple activities

查看:116
本文介绍了谷歌Analytics(分析)的Andr​​oid应用 - 处理多个活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是pretty的高兴地看到它是多么容易设置谷歌Analytics(分析)与我的应用程序,但缺乏文档有我坐在几个问题。我能找到的唯一信息与文档这里,只看着是正确的报告综合浏览量和事件从一个活动。我想报告在多个活动的页面浏览量大约事件在我的应用程序。

现在的我所有的活动的onCreate(),我呼吁:

 跟踪器= GoogleAnalyticsTracker.getInstance();
    tracker.start(UA-XXXXXXXXX,这一点);
 

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

  tracker.stop();
 

我然后跟踪浏览量和活动需要,并调度与他们一起,我执行其他HTTP请求。但我不敢肯定这是最好的方式。我应该调用start()和stop()中的每一项活动,或者我应该只调用start()和stop()在我的主发射活动​​?

解决方案

通过调用start(问题)/停止()中的每一个活动(所建议的基督徒)就是它导致了新的访问的每个活动您的用户浏览到。如果这是好的,为您的使用,那么这很好,但是,这不是大多数人的期待参观的工作方式。例如,这将使Android的比较数字,以Web或iphone数字非常困难的,因为在网络上和iPhone的地图访问到会话,而不是页面/活动。

通过调用start()的问题/停止()在您的应用程序,它会导致意外长的考察,由于Android并不保证终止应用程序的最后一项活动闭幕后。此外,如果你的应用程序确实有通知或服务的任何东西,这些后台任务可以启动你的应用程序,并导致幽灵的访问。 更新:斯蒂法诺正确指出,<一个href="http://developer.android.com/intl/fr/reference/android/app/Application.html#onTerminate%28%29">onTerminate()是从来没有所谓真正的设备上,所以没有明显的地方,将通话停止()。

通过调用start()的问题/停止()在一个单一的主的活动(所建议的奥罗拉)的是,有没有保证,活动将坚持围绕你的用户使用你的应用程序的持续时间。如果主的活动被破坏(比如释放内存),你的后续尝试写其他活动活动,GA将失败,因为会话已经停止。

此外,有一个在谷歌Analytics(分析)中的错误了通过1.2版以上,导致它保持很强的参考上下文传递的开始(),$ P $从不断获取其摧毁后,垃圾回收pventing它。根据上下文的大小,这可能是一个相当大的内存泄漏。

内存泄漏是很容易解决,它可以通过使用应用程序,而不是活动实例本身调用start()来解决。该文档或许应该更新,以反映这一点。

如。从活动里:

  //启动手动调度模式下,跟踪...
tracker.start(UA-YOUR-帐户HERE,getApplication());
 

而不是

  //启动手动调度模式下,跟踪...
tracker.start(UA-YOUR-帐户HERE,这一点); // 坏
 

对于何时调用start()/停止(),可以实现一种手工引用计数,递增每次调用Activity.onCreate(计数)和递减每个的onDestroy(),然后调用GoogleAnalyticsTracker.stop ()当计数达到零。

EasyTracker 从谷歌图书馆将照顾这对你

另外,如果你不能继承的EasyTracker活动,您可以手动在自己活动的基类自己实现:

 公共抽象类GoogleAnalyticsActivity延伸活动{

    @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);

        //需要做到这一点,每一个使用谷歌分析活动
        GoogleAnalyticsSessionManager.getInstance(getApplication())incrementActivityCount()。
    }

    @覆盖
    保护无效onResume(){
        super.onResume();

        //例如何跟踪综合浏览量事件
        。GoogleAnalyticsTracker.getInstance()trackPageView(的getClass()getSimpleName());
    }

    @覆盖
    保护无效的onDestroy(){
        super.onDestroy();

        //清除分析,使他们不持有引用了此活动
        GoogleAnalyticsTracker.getInstance()讯()。

        //需要做到这一点,每一个使用谷歌分析活动
        。GoogleAnalyticsSessionManager.getInstance()decrementActivityCount();
    }

}



公共类GoogleAnalyticsSessionManager {
    受保护的静态GoogleAnalyticsSessionManager实例;

    保护INT activityCount = 0;
    保护整数dispatchIntervalSecs;
    保护字符串apiKey;
    保护上下文的背景下;

    / **
     *注意:你应该用你的应用环境,而不是你的活动范围内,以避免内存泄漏。
     * /
    保护GoogleAnalyticsSessionManager(字符串apiKey,应用程序上下文){
        this.apiKey = apiKey;
        this.context =背景;
    }

    / **
     *注意:你应该用你的应用环境,而不是你的活动范围内,以避免内存泄漏。
     * /
    保护GoogleAnalyticsSessionManager(字符串apiKey,INT dispatchIntervalSecs,应用程序上下文){
        this.apiKey = apiKey;
        this.dispatchIntervalSecs = dispatchIntervalSecs;
        this.context =背景;
    }

    / **
     *这应该一次的onCreate()为每个活动使用GoogleAnalytics的调用。
     *这些方法是不同步的,不一般需要要,所以如果你想要做什么
     *不寻常的,你应该自己同步。
     * /
    公共无效incrementActivityCount(){
        如果(activityCount == 0)
            如果(dispatchIntervalSecs == NULL)
                。GoogleAnalyticsTracker.getInstance()启动(apiKey,背景);
            其他
                。GoogleAnalyticsTracker.getInstance()启动(apiKey,dispatchIntervalSecs,背景);

        ++ activityCount;
    }


    / **
     *这应该一次onDestrkg()为每个活动使用GoogleAnalytics的调用。
     *这些方法是不同步的,不一般需要要,所以如果你想要做什么
     *不寻常的,你应该自己同步。
     * /
    公共无效decrementActivityCount(){
        activityCount = Math.max(activityCount-1,0);

        如果(activityCount == 0)
            GoogleAnalyticsTracker.getInstance()停止()。
    }


    / **
     *获取或创建GoogleAnalyticsSessionManager的一个实例
     * /
    公共静态GoogleAnalyticsSessionManager的getInstance(应用程序){
        如果(INSTANCE == NULL)
            实例=新GoogleAnalyticsSessionManager(...,应用);
        返回实例;
    }

    / **
     *只有把这个如果你确定一个实例已经使用#getInstance(应用程序)pviously创建$ P $
     * /
    公共静态GoogleAnalyticsSessionManager的getInstance(){
        返回实例;
    }
}
 

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.

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

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

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

    tracker.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?

解决方案

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.

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().

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.

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.

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() );

instead of

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

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.

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

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;
    }
}

这篇关于谷歌Analytics(分析)的Andr​​oid应用 - 处理多个活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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