简体   繁体   中英

Android: can I use Google Analytics inside a Service?

I have an application which most of the time works in the background, as a Service. There is a lot of examples and tutorials online on how you can use Google Analytics API with EasyTracker library to track multiple Activities, but there is not a single one that explains, how to use Google Analytics API in a Service. Is it even possible?

Good news! You can. and it's quite easy.

You'll need the application context let's call it mCtx When you have this you need an instance of GoogleAnalytics, you can get it by calling

GoogleAnalytics mGaInstance = GoogleAnalytics.getInstance(mCtx);

now you need to set any parameters you want (which you would normaly put in analytics.xml when using EasyTracker).

now you need a Tracker instance:

Tracker mTracker = mGaInstance.getTracker("UA-XXXX-Y"); // your ID here

and that's basically it.. now you can send events with this tracker

mTracker.sendEvent(....);

etc..

Hope this helps. This is the very basics but GoogleAnalytics and Tracker replace the EasyTracker.

You can read more about it here: Advanced Configuration - Android SDK

Just note that until you'll see the reports on the GA website, it can take up to 24 hours.. so be patient :) or use mGaInstance.setDebug(true) to see in the logcat that it has been sent

I would suggest not to do so unless you are very sure what you are doing.

I implemented GA events in my service but it corrupted a lot of my GA stats such as session duration , daily percentage of new sessions , daily sessions etc. GA thinks that events are caused after a screen view and so it pushes the GA event with a screen name " (not set) ". Since services ran in the background a lot of times, it ended up corrupting the various stats. The real-time display of active users also went wrong.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM