fantasy1022
2/19/2018 - 9:06 AM

GATracker file

class GATracker : BaseTracker<Event> {

    private lateinit var tracker: Tracker

    constructor(context: Application, isDebug: Boolean) : super(context, isDebug)

    override fun getTrackerTarget(): Long {
        return TARGET_GA
    }

    override fun setupTracker(context: Application, isDebug: Boolean) {
        val analytics = GoogleAnalytics.getInstance(context)
        tracker = if (isDebug) analytics.newTracker(DEBUG_TOKEN) else analytics.newTracker(RELEASE_TOKEN)
    }

    override fun acceptEvent(event: Event): Boolean {
        return (event is ScreenEvent) || !event.params.isEmpty
    }

    override fun transformEvent(event: Event): Event {
        return event
    }

    override fun postEvent(transformedEvent: Event) {
        if (transformedEvent is ScreenEvent) {
            tracker.setScreenName(transformedEvent.screenName)
            tracker.send(HitBuilders.ScreenViewBuilder().build())
        } else {
            tracker.send(getEventMap(transformedEvent))
        }
    }

    private fun getEventMap(event: Event): Map<String, String> {
        val eventBuilder = HitBuilders.EventBuilder()
                .setCategory(event.params[Event.CATEGORY])
                .setAction(event.params[Event.ACTION])
                .setLabel(event.params[Event.LABEL])

        return eventBuilder.build()
    }

}