1
0

More than 1 year has passed since last update.

Firebase Analytics実装方法

Posted at

初めに

今回は、楽にAnalyticsでlogEventを実装できる様にするやり方を備忘録として書いていこうと思います

実装方法

まず、イベントを渡す用のクラスを作成します

abstract class TrackingEvent(
    val key: String,
    val parameters: Map<String, Any> = emptyMap(),
)

次に、logEventを実装するためのInterfaceと本実装用のクラスを実装します

class TrackingService @Inject constructor(
    private val firebaseAnalytics: FirebaseAnalytics
) : TrackingServiceInterface {
    override fun track(trackingEvent: TrackingEvent) {
        firebaseAnalytics.logEvent(
            trackingEvent.key,
            trackingEvent.parameters.toBundle(),
        )
    }
}

// TrackingEventのパラメータをBundleに詰め替える拡張関数
fun Map<String, Any>.toBundle(): Bundle = Bundle().apply {
    this@toBundle.forEach { (key, value) ->
        when (value) {
            is String -> this.putString(key, value)
            is Int -> this.putInt(key, value)
            is Boolean -> this.putBoolean(key, value)
            else -> throw IllegalArgumentException()
        }
    }
}

最後にこれらを共通して使える様にDI用のModuleを実装します

// logEvent用
    @Provides
    @Singleton
    fun provideEventTrackingService(
        impl: TrackingServiceImpl
    ): TrackingService = impl
// firebaseAnalytics用
    @Provides
    @Singleton
    fun provideFirebaseAnalytics(
        @ApplicationContext context: Context
    ): FirebaseAnalytics = FirebaseAnalytics.getInstance(context)
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0