Main navigation

Android Firebase Analytics Tutorial

adsense

Creating a New Project

  1. Go to File → New → New Project and enter your Application Name.
  2. Enter company domain, this is used to uniquely identify your App’s package worldwide. Remember to use the same package name as used in the firebase console.
  3. Choose project location and minimum SDK and on the next screen choose Basic Activity, since we would be adding most of the code Ourselves. Then Click on Next.
  4. Choose an Activity Name. Make sure Generate Layout File check box is selected, Otherwise we have to generate it ourselves.Then click on Finish. We have used the default Activity Name MainActivity.

Gradle will configure your project and resolve the dependencies, Once it is complete proceed for next steps.

Add Permissions and Dependencies

  1. After Gradle syncs the project, add the google-services.json file to your project’s app folder as shown below.
  2. Android Firebase Analytics Tutorial -add google-services.json

  3. Since we need to connect to the Network add the Internet permission in AndroidManifest.xml file.
  4. <uses-permission android:name="android.permission.INTERNET"/>
    
  5. Now open your project’s build.gradle from the project’s home directory and add the following dependency.
  6. build.gradle

    	classpath 'com.google.gms:google-services:3.0.0'
    
  7. Next, open your app’s build.gradle from the and add the following at the end.
  8. build.gradle

    	apply plugin: 'com.google.gms.google-services'
    
  9. Also add the following dependency in the dependency section.
  10.     compile 'com.google.firebase:firebase-core:9.0.2'
    

Logging Events in Android Firebase Analytics

We will use a Java Model class Book.java to log events. So create a new Java class Book.java and add the following code.

Book.java

package com.androidtutorialpoint.firebaseanalyticstutorial;

public class Book {
    private int bookId;
    private String bookTitle;

    public int getBookId() {
        return bookId;
    }
    public void setBookId(int bookId) {
        this.bookId = bookId;
    }
    public String getBookTitle() {
        return bookTitle;
    }
    public void setBookTitle(String bookTitle) {
        this.bookTitle = bookTitle;
    }
}

Now in the MainActivity.java, we need to intialize the Android Firebase Analytics using

firebaseAnalytics = FirebaseAnalytics.getInstance(this);

We will need this instance to set up the user events.Next, we create a bundle to Log the User Id and User Name using logEvent() method.

Add the following code to your MainActivity.java.

Bundle bundle = new Bundle();
bundle.putInt(FirebaseAnalytics.Param.ITEM_ID, book.getBookId());
bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, book.getBookTitle());
bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "Book");
firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);

Next, we enable this device for collection of events to Android Firebase Analytics using the setAnalyticsCollectionEnabled() method.

And set the minimum user engagement time before starting to collect the events.
To quickly enable the session, we are setting it to 2 seconds. For this, we need to pass the time in milliseconds to setMinimumSessionDuration() method. Please note that by default it is 10 seconds.

We will also set the duration of inactivity, before destroying the session as 5 minutes using setSessionTimeoutDuration() method.

firebaseAnalytics.setAnalyticsCollectionEnabled(true);
firebaseAnalytics.setMinimumSessionDuration(2000);
firebaseAnalytics.setSessionTimeoutDuration(300000);

Setting User Properties

Android Firebase Analytics will log some user properties as discussed earlier, however, you can also set up to 25 different Analytics User Properties for your app.

To add a user property, we will register the property in the dashboard of Android Firebase Analytics console under User Properties Tab.

We have registered two user properties as FAVOURITE_BOOK and FAVOURITE_AUTHOR which we will be taking as input from the user.

Add the following code in your content_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:id="@+id/content_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.androidtutorialpoint.firebaseanalyticstutorial.MainActivity"
    tools:showIn="@layout/activity_main">

    <EditText
        android:id="@+id/favBookEditText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter your Favourite Book" />
    <EditText
        android:id="@+id/favAuthorEditText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter your Favourite Author" />
    <Button
        android:id="@+id/addButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Add Favourites !!" />
</RelativeLayout>

Next Add this code to set the User Properties using the setUserProperty() method.
The following example adds a favorite author and favorite book for the user once a user clicks on the add button.

addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //Sets the Favourite Book property.
                firebaseAnalytics.setUserProperty("FAVOURITE_BOOK",favouriteBook.getText().toString());

                //Sets the Favourite Author property.
                firebaseAnalytics.setUserProperty("FAVOURITE_AUTHOR",favouriteAuthor.getText().toString());

                //Show a toast message
                Toast.makeText(MainActivity.this,"User Properties Added",Toast.LENGTH_SHORT).show();


            }
        });

Once you click on the Add Favorite Button, the user properties will be updated in the firebase console and logged in the LogCat as shown below.
Android Firebase Analytics - Log User Defined Properties

Complete code for MainActivity.java

package com.androidtutorialpoint.firebaseanalyticstutorial;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.firebase.analytics.FirebaseAnalytics;
import java.util.Random;

public class MainActivity extends AppCompatActivity {
    private FirebaseAnalytics firebaseAnalytics;
    String[] books = {"The Hunger Games","Harry Potter","Pride and Prejudice","Twilight"};
    private EditText favouriteBook;
    private EditText favouriteAuthor;
    private Button addButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        firebaseAnalytics = FirebaseAnalytics.getInstance(this);

        favouriteBook = (EditText)findViewById(R.id.favBookEditText);
        favouriteAuthor = (EditText)findViewById(R.id.favAuthorEditText);
        addButton = (Button)findViewById(R.id.addButton);

        Book book = new Book();
        book.setBookId(1);
        // choose random food name from the list
        book.setBookTitle(randomBook());

        Bundle bundle = new Bundle();
        bundle.putInt(FirebaseAnalytics.Param.ITEM_ID, book.getBookId());
        bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, book.getBookTitle());

        //Logs an app event.
        firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);

        //Set whether analytics collection is enabled for this app on this device.
        firebaseAnalytics.setAnalyticsCollectionEnabled(true);

        //Set the minimum engagement time required before starting a session.
        firebaseAnalytics.setMinimumSessionDuration(2000);

        //Set the duration of inactivity that terminates the current session. The default value is 1800000 (30 minutes).
        firebaseAnalytics.setSessionTimeoutDuration(300000);

        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //Sets the Favourite Book property.
         firebaseAnalytics.setUserProperty("FAVOURITE_BOOK",favouriteBook.getText().toString());
                //Sets the Favourite Author property.
                firebaseAnalytics.setUserProperty("FAVOURITE_AUTHOR",favouriteAuthor.getText().toString());

                //Show a toast message
                Toast.makeText(MainActivity.this,"User Properties Added",Toast.LENGTH_SHORT).show();
            }
        });
    }
    private String randomBook() {
        Random rand = new Random();
        return books[rand.nextInt(4)];
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

That’s all folks, run your app in the emulator or an actual device. Interact with your app for about 30 seconds and also add your favorite book and favorite author and click on add button. Now after some time, verify that it gets reflected in the Android Firebase Analytics Dashboard .

You can filter the statistics based upon the user properties, as shown below.

Android Firebase Analytics - Apply filter on User Dashboard

It might take some hours for data to be reflected properly in the console.



What’s Next ??

After Integratig Android Firebase Analytics. You can add Firebase Login to autheniticate user or notifications and messaging to your app using Firebase Cloud Messaging Tutorial. You can also use Firebase send email service to send password reset email to the users.

In case you want to store data in Firebase Database, please visit our tutorial on Firebase Database

We hope you liked our Android Firebase Analytics Integration Example, please leave comments in the comment section below in the case of any doubts.

Soon We will be covering articles on how to add Facebook and Google Sign-In using Firebase. Interested developers can explore more about firebase hosting and firebase security.
Till then stay tuned for more tutorials.. and Don’t forget to subscribe our blog for latest android tutorials. Also do Like our Facebook Page or Add us on Twitter.

To download the full code for the Android Firebase Analytics app, Click on the Download Now link below.

Android Firebase Analytics Download Now


Reader Interactions

Comments

  1. Hi,
    i have refer your tutorial for firebase analytics but on firebase console and i have created my custom user property but is not updating on console please help me.
    Thank You

Leave a Reply

Advertisment ad adsense adlogger