Devesh Rx Logo
Devesh Rx

πŸš€ Google Analytics for Android, From Setup to Production! πŸ“±πŸ“Š

April 30, 2025

πŸš€ Google Analytics for Android, From Setup to Production! πŸ“±πŸ“Š

Understanding how users interact with your Android application is crucial for making informed decisions and improving the user experience. Google Analytics, seamlessly integrated via the Firebase SDK (a.k.a Firebase Analytics), provides powerful tools to gather these insights.

This guide will walk you through integrating Firebase Analytics into your Android project, covering:

  1. The Basics: Setting up Firebase Analytics in your Android app.
  2. Debugging Events: Safely testing your analytics implementation without affecting production data.

Let’s get started!

Getting Started: Setting Up Firebase Analytics

First things first, you need an Android project. We’ll assume you have a basic, empty Android app ready.

Adding Dependencies:

You need to add the Firebase Analytics SDK to your project. There are two main ways:

  • Automatic Method (via Android Studio): Go to Tools > Firebase. In the Assistant panel, find Analytics, click Get started with Google Analytics, connect your Firebase account, and click Add Analytics to your app. Android Studio handles the dependency additions automatically.
  • Manual Method: This gives you more control and understanding.
    • Project-level build.gradle(.kts) file: Ensure the Google Services plugin is included in your plugins block.
      // Example for build.gradle (Groovy)
      plugins {
          id 'com.android.application' version '...' apply false
          id 'org.jetbrains.kotlin.android' version '...' apply false
          // Add this line if not present
          id 'com.google.gms.google-services' version '4.4.1' apply false // Use the latest version
      }
      
      
      // Example for build.gradle.kts (Kotlin)
      plugins {
          alias(libs.plugins.android.application) apply false
          alias(libs.plugins.jetbrains.kotlin.android) apply false
          // Add this line if not present
          alias(libs.plugins.google.gms.google.services) apply false
      }
    • Module-level (app) build.gradle(.kts) file: Apply the Google Services plugin at the top and add the Firebase Analytics dependency.
      // Example for build.gradle (Groovy)
      plugins {
          id 'com.android.application'
          id 'org.jetbrains.kotlin.android'
          // Apply the plugin
          id 'com.google.gms.google-services'
      }
      
      dependencies {
          // ... other dependencies
          // Import the Firebase BoM (Bill of Materials)
          implementation platform('com.google.firebase:firebase-bom:33.1.0') // Use the latest BoM version
      
          // Add the dependency for Firebase Analytics
          implementation 'com.google.firebase:firebase-analytics-ktx'
          // or implementation 'com.google.firebase:firebase-analytics' for Java
      }
      
      // Example for build.gradle.kts (Kotlin)
      plugins {
          alias(libs.plugins.android.application)
          alias(libs.plugins.jetbrains.kotlin.android)
          // Apply the plugin
          alias(libs.plugins.google.gms.google.services)
      }
      
      dependencies {
          // ... other dependencies
          // Import the Firebase BoM (Bill of Materials)
          implementation(platform(libs.firebase.bom)) // Assumes bom is defined in libs.versions.toml
      
          // Add the dependency for Firebase Analytics
          implementation(libs.firebase.analytics) // Assumes analytics is defined in libs.versions.toml
      }
    • Sync Project: Click Sync Now in the notification bar that appears after editing Gradle files.

Connecting to Firebase & Getting google-services.json:

The SDK needs to know which Firebase project to send data to. This is configured using the google-services.json file.

  1. Go to the Firebase Console.
  2. Select your project or create a new one.
  3. In the project overview, click the + Add app button and select the Android icon.
  4. Enter your app’s package name (find it in your module-level build.gradle file, usually under namespace or applicationId).
  5. Optionally add an app nickname and the SHA-1 signing certificate hash (useful for other Firebase services, optional for Analytics basics).
  6. Click Register app.
  7. Download the google-services.json file.
  8. Switch your Android Studio project view from Android to Project (using the dropdown in the top-left of the Project window).
  9. Copy the downloaded google-services.json file into your project’s app module root directory (e.g., YourProjectName/app/).
  10. Switch back to the Android view.
  11. In the Firebase console, click Next, skip the β€œAdd Firebase SDK” steps (we did this manually), and click Continue to console.
  12. Build your project (Build > Make Project) to ensure everything is configured correctly. A successful build means the initial setup is complete!

Implementing Analytics in Your Code

Now, let’s start logging events.

Initialize the SDK:

In your MainActivity.kt (or your primary Activity/Application class), get an instance of FirebaseAnalytics.

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.google.firebase.analytics.FirebaseAnalytics
import com.google.firebase.analytics.ktx.analytics // KTX extension
import com.google.firebase.ktx.Firebase // KTX extension

class MainActivity : AppCompatActivity() {

    // Declare FirebaseAnalytics variable
    private lateinit var firebaseAnalytics: FirebaseAnalytics

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Obtain the FirebaseAnalytics instance
        firebaseAnalytics = Firebase.analytics

        // Example: Log a basic event when the app starts
        logAppStartEvent()
    }

    // Function to log a custom event
    private fun logAppStartEvent() {
        val eventName = "app_start_event" // Choose a descriptive name
        val params = Bundle().apply {
            putString("demo_param_id", "12345")
            putString("demo_param_name", "initial_load")
            // You can add standard parameters too using FirebaseAnalytics.Param constants
            // putString(FirebaseAnalytics.Param.SCREEN_NAME, "MainActivity")
        }
        firebaseAnalytics.logEvent(eventName, params)

        // If you don't need parameters:
        // firebaseAnalytics.logEvent("simple_app_start", null)
    }
}

Logging Custom Events:

The core of Firebase Analytics is logging events. You use the logEvent() method:

  • name: A String representing the event name (use snake_case, e.g., share_image, add_to_cart). Stick to recommended event names where possible, or define clear custom names.
  • params: An optional Bundle containing key-value pairs for event parameters (e.g., item ID, item name, screen name). Parameter keys are Strings, and values can be String, long, or double.

Conclusion

Integrating Firebase Analytics into your Android app is a straightforward process that yields immense value. By setting up the SDK, logging relevant events, and utilizing DebugView for testing, you can gain deep insights into user behavior. A structured approach, like using a helper module and constants, makes implementation cleaner and more maintainable in production applications. Start tracking today and use the data to build better apps!

~ ~ THANK YOU FOR READING ~ ~

Share: