ZOFTINO.COM android and web dev tutorials

Android Adding Google Analytics Firebase

Google analytics helps in understanding how your app is being used. It captures events and user properties. The captured data is available in Firebase console for you to get insights into your app user’s behavior.

In this post, you can learn how to add Google analytics for Firebase to Android app with an example, how to add custom event and custom event parameter and how to view analytics reports.

Creating Firebase Project

Login to firebase console, here is the link to firebase console. Click add project on the main page of Firebase console.

Firebase console add project

Enter project name and click create project.

Firebase console add project form

Adding Firebase to Android App

On Firebase main screen, click your firebase project created above, then click add firebase to your android app.

Firebase console add firebase to android project

Enter package name from your android project, enter nick name, and enter optional SHA1. You need to enter SHA1 if you use Google sign in. Then click register app.

Firebase console add firebase to android project form

Then download google-services.json file and save it in app folder in your android project.

Firebase console add firebase to android project form

Then to install Firebase SDK and setup your android project, add 'com.google.gms.google-services' plug-in to bottom of app level gradle build file.

apply plugin: 'com.google.gms.google-services'

Add gsm library 'com.google.gms:google-services:3.1.0' to classpath in project level gradle build file.


buildscript {
    ....
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-beta7'
        classpath 'com.google.gms:google-services:3.1.0'
    }
}

Then add analytics library to project by adding below entries to build.gradle file.

    implementation 'com.google.firebase:firebase-core:11.8.0'

Logging Events

By default without adding any code, Google analytics captures events and user properties. To log your app specific events, first you need to get FirebaseAnalytics object by calling get instance on it. To FirebaseAnalytics object, you can add user id if user is authenticated and current screen details to track screens by calling setUserId and setCurrentScreen methods respectively.

Then create a bundle by adding values for predefined or custom parameters that you want to track. Then log event by calling logEvent method on FirebaseAnalytics object passing event name and bundle as shown below.

 firebaseAnalytics = FirebaseAnalytics.getInstance(this);
Bundle bundle = new Bundle();
bundle.putString("Contact", "xyz");
bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "text");
firebaseAnalytics.logEvent("Add_Contact", bundle);

Logging User Properties

As mentioned before, without adding any code, firebase analytics captures user properties. If you want to capture data for custom user properties, first you need add the user property in Firebase console by clicking user properties in left navigation and then adding the property name.

Firebase console analytics custom user property

Once the user property has been registered, you can add the property to analytics by calling setUserProperty method on FirebaseAnalytics object.

firebaseAnalytics.setUserProperty("user_stage", "advanced");

Firebase Console Analytics Reporting

In firebase console, go to dash board, events or other tabs in the left navigation to view analytics data for your app. In the events tab, you can click any event and see details like event demographics, event location and events per session.

Firebase console analytics reporting

Adding Custom Event Parameters

If you want to track additional information for any event, you need to first register custom parameters for the event you want to add extra information for by clicking the event in events report, then clicking add events parameters button, then adding custom event parameter name, selecting type and saving it.

Firebase console analytics reporting events add custom event parameter

After the event parameter has been registered, you can add it to bundle and pass it to logEvent method in your app.

 Bundle bundle = new Bundle();
bundle.putString("Contact", "klmn");
firebaseAnalytics.logEvent("Add_Contact", bundle);

Below is analytics example activity and layout.

Activity

 import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;

import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

import zoftino.com.firestore.EmailPasswordAuthActivity;
import zoftino.com.firestore.R;

public class FirebaseAnalyticsActivity extends AppCompatActivity {
    private static final String TAG = "FirebaseAnalyticsActivity";

    private FirebaseUser user;
    private FirebaseAnalytics firebaseAnalytics;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.analytics_layout);

        user = FirebaseAuth.getInstance().getCurrentUser();
        if(user == null){
            Intent i = new Intent();
            i.setClass(this, EmailPasswordAuthActivity.class);
            startActivity(i);
        }

        firebaseAnalytics = FirebaseAnalytics.getInstance(this);
        firebaseAnalytics.setUserId(user.getUid());
        firebaseAnalytics.setUserProperty("user_stage", "advanced");
        firebaseAnalytics.setCurrentScreen(this, "contacts", "actions");
        setButtonListeners();
    }

    private void setButtonListeners(){
        findViewById(R.id.add_contact).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                addContact();
            }
        });
        findViewById(R.id.edit_contact).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                editContact();
            }
        });
        findViewById(R.id.delete_contact).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                deleteContact();
            }
        });
    }

    private void addContact(){
        Bundle bundle = new Bundle();
        bundle.putString("Contact", "xyz");
        bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "text");
        firebaseAnalytics.logEvent("Add_Contact", bundle);

        Toast.makeText(FirebaseAnalyticsActivity.this,
                "Contact has been added",
                Toast.LENGTH_SHORT).show();
    }
    private void editContact(){
        Bundle bundle = new Bundle();
        bundle.putString("Contact", "abc");
        bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "text");
        firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);

        Toast.makeText(FirebaseAnalyticsActivity.this,
                "Contact has been updated",
                Toast.LENGTH_SHORT).show();
    }
    private void deleteContact(){
        Bundle bundle = new Bundle();
        bundle.putString("Contact", "klmn");
        bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "text");
        firebaseAnalytics.logEvent("Delete_Contact", bundle);

        Toast.makeText(FirebaseAnalyticsActivity.this,
                "Contact has been deleted",
                Toast.LENGTH_SHORT).show();
    }
}

Layout

 <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="zoftino.com.firebase.analytics.FirebaseAnalyticsActivity">
    <Button
        android:id="@+id/add_contact"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:layout_marginRight="8dp"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:text="Add Contact"/>
    <Button
        android:id="@+id/edit_contact"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginRight="8dp"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/add_contact"
        android:text="Edit Contact"/>
    <Button
        android:id="@+id/delete_contact"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginRight="8dp"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/edit_contact"
        android:text="Delete Contact"/>
</android.support.constraint.ConstraintLayout>