Android Firebase – Integrating Analytics

Another interesting feature that firebase offers is the Firebase Analytics. Free, simple and unlimited. Sounds like a scam? Luckily google is not joking. Analytics integrates across Firebase features and provides you with unlimited reporting for up to 500 distinct events that you can define using the Firebase SDK.

Firebase Analytics reports help you understand clearly how your users behave, which enables you to make informed decisions regarding app marketing and performance optimizations. Firebase Analytics helps you understand how people use your app.

android-firebase-analytics-tutorial

The Firebase SDK automatically captures a number of events and user properties and also allows you to define your own custom events to measure the things that uniquely matter to your business. Once the data is captured, it’s available in a dashboard through the Firebase console. This dashboard provides detailed insights about your data — from summary data such as active users and demographics, to more detailed data such as identifying your most purchased items.

Firebase Analytics also integrates with a number of other Firebase features. For example, it automatically logs events that correspond to your Firebase Notifications and provides reporting on the impact of each campaign.
Here are the events and user properties that Firebase Analytics offers without adding any additional code to you project.

Automatically Collected Events

Automatically collected events are triggered by basic interactions with your app. As long as you use the Firebase SDK, you don’t need to write any additional code to collect these events. Below are list of event collected automatically.

Event nameTriggered…
first_openwhen a user opens the app for the first time.

This event is not triggered when a user downloads the app onto a device, but instead when he or she first uses it. To see raw download numbers, look in Google Play Developer Console or in iTunesConnect.

in_app_purchasewhen a user completes an in-app purchase that is processed by the App Store on iTunes or Google Play. The product ID, product name, currency, and quantity are passed as parameters.

This event is triggered only by versions of your app that include the Firebase SDK. Also, subscription revenue, paid app-purchase revenue, and refunds are not automatically tracked, and so your reported revenue may differ from the values you see in the Google Play Developer Console.

user_engagementperiodically, while the app is in the foreground.
session_startwhen a user engages the app for more than the minimum session duration.
app_updatewhen the app is updated to a new version and launched again. The previous app version id is passed as a parameter.

app_update varies from Daily upgrades by device, which is reported by Google Play Developer Console whether or not the app is launched again after update.

app_removewhen an application package is removed or “uninstalled” from an Android device.

This event is different from the Daily uninstalls by device and Daily uninstalls by user metrics, which are both reported by Google Play Developer Console. The app_remove event counts the removal of application packages, regardless of the installation source, and the count changes depending on the date range you are using for the report. The Daily uninstalls by device and Daily uninstalls by user metrics count the removal of application packages only when they were installed from Google Play, and are reported on a daily basis.

os_updatewhen the device operating system is updated to a new version. The previous operating system version id is passed as a parameter.
app_clear_datawhen the user resets/clears the app data, removing all settings and sign-in data.
app_exceptionwhen the app crashes or throws an exception.
notification_foregroundwhen a notification sent by Firebase Cloud Messaging is received while the app is in the foreground.
notification_receivewhen a notification sent by Firebase Cloud Messaging is received by a device when the app is in the background. Android apps only.
notification_openwhen a user opens a notification sent by Firebase Cloud Messaging.
notification_dismisswhen a user dismisses a notification sent by Firebase Cloud Messaging. Android apps only.
dynamic_link_first_openwhen a user opens the app for the first time via a dynamic link. iOS app only.
dynamic_link_app_openwhen a user opens the app via a dynamic link. iOS apps only.
dynamic_link_app_updatewhen the app is updated to a new version via a dynamic link. iOS apps only.

Automatically Collected User Properties

Firebase automatically collects user properties too such as App version, Device model, Gender, Age, Interests, OS version, New/Established. This information can be seen the dashboard directly without writing any additional code.

Integrating Firebase Analytics

Now we’ll create a simple app which collects user chosen food on firebase analytics dashboard. All we do is collect user id along with the food he is choosing.

1. First thing you need to do is go to https://firebase.google.com/ and make an account to gain access to their console. After you gain access to the console you can start by creating your first project.

2. Give the package name of your project (mine is info.androidhive.firebase) in which you are going to integrate the Firebase. Here the google-services.json file will be downloaded when you press add app button.

android-adding-firebase-analytics

3. Create a new project in Android Studio from File ⇒ New Project. While filling the project details, use the same package name which you gave in firebase console. In my case I am using same info.androidhive.firebase.

4. Open AndroidManifest.xml and add the INTERNET permission as we need to make network calls.

<uses-permission android:name="android.permission.INTERNET" />

5. Paste the google-services.json file to your project’s app folder. This step is very important as your project won’t build without this file.

6. Now open the build.gradle located in project’s home directory and add firebase dependency.

dependencies {
        classpath 'com.android.tools.build:gradle:2.1.2'
        classpath 'com.google.gms:google-services:3.0.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }

7. Open app/build.gradle and add firebase core dependency. At the very bottom of the file, add apply plugin: ‘com.google.gms.google-services’

dependencies {
    compile 'com.google.firebase:firebase-core:9.0.2'
}

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

8. Add new class and name it Food.java. This will be our plain mega simple POJO just for the sake of testing.

package com.androidhive.info.firabaseanalytisc;

public class Food {

    private int id;
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

9. Open MainActivity.java and add the following.

package com.androidhive.info.firabaseanalytisc;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.google.firebase.analytics.FirebaseAnalytics;

public class MainActivity extends AppCompatActivity {

    private FirebaseAnalytics firebaseAnalytics;
    String[] foods;

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

        foods = new String[]{"Apple", "Banana", "Grape", "Mango", "Orange"};

        // Obtain the Firebase Analytics instance.
        firebaseAnalytics = FirebaseAnalytics.getInstance(this);

        Food food = new Food();
        food.setId(1);
        // choose random food name from the list
        food.setName(foods[randomIndex()]);

        Bundle bundle = new Bundle();
        bundle.putInt(FirebaseAnalytics.Param.ITEM_ID, food.getId());
        bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, food.getName());

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

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

        //Sets the minimum engagement time required before starting a session. The default value is 10000 (10 seconds). Let's make it 20 seconds just for the fun
        firebaseAnalytics.setMinimumSessionDuration(20000);

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

        //Sets the user ID property.
        firebaseAnalytics.setUserId(String.valueOf(food.getId()));

        //Sets a user property to a given value.
        firebaseAnalytics.setUserProperty("Food", food.getName());
    }

    private int randomIndex() {
        int min = 0;
        int max = foods.length - 1;
        Random rand = new Random();
        return min + rand.nextInt((max - min) + 1);
    }
}

And here is the explanation of the code in detail.

firebaseAnalytics = FirebaseAnalytics.getInstance(this);

This is the part where you simply call the instance of the FirebaseAnalytics. After we get the instance we can set up few events.

Bundle bundle = new Bundle();
bundle.putInt(FirebaseAnalytics.Param.ITEM_ID, food.getId());
bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, food.getName());
firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);

Here we create a bundle and pass it to the logEvent. We can also set whether analytics collection is enabled for this app on this device.

firebaseAnalytics.setAnalyticsCollectionEnabled(true);

This next line sets the minimum engagement time required before starting a session. The default value is 10000 ( 10 seconds) . Let’s make it 5 second.

firebaseAnalytics.setMinimumSessionDuration(5000);

Here we can set the duration of inactivity that terminates the current session. The default value 1800000 (30 minutes). Let’s make it 10.

firebaseAnalytics.setSessionTimeoutDuration(1000000);

Now let’s set some of the user properties as well. This line set the user ID property.

firebaseAnalytics.setUserId(String.valueOf(food.getId()));

And this set a user property to a given value.

firebaseAnalytics.setUserProperty("Food", food.getName());

Thats it. Really simple as it should be. Hope you will enjoy using the Firebase Analytics. Note: You might not be able to see the changes and reports right away but within 24 hours.