Google Analytics for Android using multiple Activities

佐手、 提交于 2019-12-05 20:46:47

After studying the lifecycle of an Activity, I came to the following conclusion.

When switching from an Activity A to another Activity B, the onStop method of A is called AFTER the onStart method of B. What I then did was increasing a reference counter every time the (static) tracker is accessed in an onStart method. In the onStop method, I would first check whether the reference counter was 0, and stop the tracker if it was. At the end of the onStop method, I would decrease the reference counter.

This seems to be working quite well at this moment, and should also work when the application has multiple Activities that can act as an entry point.

evaneus

Repeating an answer that I posted here: Google Analytics in Android app - dealing with multiple activities

The approach I am using is to use a Bound Service (I happen to be using one already so was spared the creation of extra boiler plate code.)

A Bound Service will only last as long as there are Activities bound to it. All the activities in my app bind to this service, so it lasts only as long as the user is actively using my application - therefore very much a real 'session'.

I start the tracker with a singleton instance of Application which I have extended and added a static getInstance() method to retrieve the instance:

// Non-relevant code removed

public IBinder onBind(Intent intent) {
    tracker = GoogleAnalyticsTracker.getInstance();
    tracker.startNewSession(PROPERTY_ID, MyApp.getInstance());
}


public boolean onUnbind(Intent intent) {
    tracker.stopSession();
}

See: http://developer.android.com/guide/topics/fundamentals/bound-services.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!