Google Analytics for Android using multiple Activi

2019-05-15 01:21发布

I'm trying to integrate Google Analytics into my Android project using the information on the website of the respective SDK. However, there is very little documentation available. My project has 6 different Activities and I noticed that using the method on the website results in a unique visit in Google Analytics for each Activity that is being opened, even if it's still in the same session. Apparently, Google Analytics for Android never reuses a previously used session.

Their method is to start tracking activity in onCreate and then stop tracking in onDestroy. The problem I have with this is that a session will stay active if a user presses the home button instead of the back button, since the Activity will not be destroyed. Therefore I chose to do it in onResume and onPause instead but that means that new sessions gets opened when a new Activity is opened.

Does anyone know any way to really track a single session over multiple Activities?

2条回答
兄弟一词,经得起流年.
2楼-- · 2019-05-15 02:10

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.

查看更多
甜甜的少女心
3楼-- · 2019-05-15 02:26

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

查看更多
登录 后发表回答