How to use Google Analytics in Android kotlin
you should initialize google analytics in this function:
@Synchronized
fun getDefaultTracker(): Tracker? {
var tracker: Tracker? = null
analytics = GoogleAnalytics.getInstance(context) // here pass your activity instance
analytics?.let {
tracker = it.newTracker(R.xml.global_tracker)
}
return tracker
}
Yes Google has newer analytics tools that they would prefer we use but some of us have business reasons to continue with the old v4 analytics.
Starting with their original suggested implementation, which was written in java, here is a Kotlin version.
class MyApplication: Application() {
companion object {
lateinit var googleAnalytics: GoogleAnalytics
}
override fun onCreate() {
super.onCreate()
googleAnalytics = GoogleAnalytics.getInstance(this)
}
}
Next Google suggests the Application instance generate and provide a shared instance of the Tracker for use by your various Activities and Fragments. But in Kotlin, I found it much cleaner to set up a separate companion object...
object Analytics {
var tracker: Tracker
init {
@Synchronized
tracker = MainApplication.googleAnalytics.newTracker(R.xml.global_tracker)
}
}
Firing screen views and events throughout your app can be done as follows:
Analytics.tracker.setScreenName("Screen Name")
Analytics.tracker.send(HitBuilders.ScreenViewBuilder().build())
Analytics.tracker.send(
HitBuilders.EventBuilder()
.setCategory("foo")
.setAction("bar)
.setLabel("baz")
.build()
)