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 name Triggered…
first_open when 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_purchase when 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_engagement periodically, while the app is in the foreground.
session_start when a user engages the app for more than the minimum session duration.
app_update when 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_remove when 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_update when the device operating system is updated to a new version. The previous operating system version id is passed as a parameter.
app_clear_data when the user resets/clears the app data, removing all settings and sign-in data.
app_exception when the app crashes or throws an exception.
notification_foreground when a notification sent by Firebase Cloud Messaging is received while the app is in the foreground.
notification_receive when a notification sent by Firebase Cloud Messaging is received by a device when the app is in the background. Android apps only.
notification_open when a user opens a notification sent by Firebase Cloud Messaging.
notification_dismiss when a user dismisses a notification sent by Firebase Cloud Messaging. Android apps only.
dynamic_link_first_open when a user opens the app for the first time via a dynamic link. iOS app only.
dynamic_link_app_open when a user opens the app via a dynamic link. iOS apps only.
dynamic_link_app_update when 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.

Ravi is hardcore Android programmer and Android programming has been his passion since he compiled his first hello-world program. Solving real problems of Android developers through tutorials has always been interesting part for him.
  • great Job .. thank you

  • ecwid

    Thanks for such a Nice Tutorial Ravi..

  • Ng Clement

    Hi,Ravi. May you do some tutorial about opencv library like using opencv to detect face on a static photo?? Thx

    • Yes, but it might take time. Meanwhile you can get opencv (they are supporting android now) and try their sample codes.

      • Ng Clement

        Thank you for your reply and looking forwards to see your tutorial. I have learned so many things in your website. It is very useful for me.

  • Jothiprabhakar Sivaprakasam

    Thanks Man πŸ™‚

  • Todsavorn Pholsena

    Thank you πŸ™‚

  • tamer

    Hello

    thank you very much for this tutorial .

    Regards

  • Mudit
  • Nick George

    This is a fantastic post on new Google Firebase. Any intentions of adding a Firebase DB tutorial?

    • All the firebase base modules will be covered. Don’t worry

  • ÑÀMΓ Γ± Arora

    You have really great tutorials on this site! Can you do one on handling notifications using firebase? Thanks once again for the great post.

    • Yeah, It will be posted in next week.

      • Mezoo0

        Thank you Mr. Ravi. And Where are you Mr. Ravi. We are waiting you. To Complete All topics under firebase. Like Database and Notification and handling some function on a firebase.

  • Akshay

    Thumbs up for Ravi.. seriously you are like dronacharya to me. Helping me on every part of my coding.

  • Achyut Bhandiwad

    Great tutorial.. waiting for your other firebase module tutorials πŸ™‚

  • Rahul Rai

    Hi Ravi can we have a tutorial related to audio fingerprinting or audio recognition (songs). There’s not a single tutorial on this on internet. Thanx and pls reply.

    • Normally we implement these kind of operations on server side as we can’t have lot of audio stored in the app. What you can do is send the audio from android to server, server performs the validation / match and returns the response.

  • surya ramiah

    ravi sir u should make video tutorial

  • avinash

    Where can i see the custom bunble values in firebase console

  • Shafayat Mamun

    Can you make a tutorial about android mvp(model-view-presenter) architecture?

  • Dia Bader

    Nice tutorial and we are waiting a wonderful article form you πŸ™‚ again thank you so much

  • Vinu Chacko

    Nice tutorial Sir.
    Am a beginner in fire base. So I have a big doubt, Can we use server side code for sending push notification to android apps using fire base? Is it possible? Am developing an android app that need push notification, So which is the best method GCM or FCM. .? Hope my question is clear. Please give me an answer.
    Thank you

    • Vipin Negi

      Yeah you can use server side code for sending push notification.
      Unfortunately GCM has been discontinued and cannot be used further on any new applications. FCM is better than GCM and more reliable IMHO. So go ahead with FCM.

      With FCM, you can send two types of messages to clients:
      1. Notification messages, sometimes thought of as “display messages.”
      2. Data messages, which are handled by the client app.

      make sure you used the ‘Data Messages’ to send notification configured on server.

    • ali masri

      you can Download : “Master Android” & Learn Firebase From Zero To Hero

  • titi

    lol HARDCORE Android MMMMMMMMMDR !!!!!

  • Faisal Mohammed

    Ravi, great job. Insightful.
    Any plans to plot a sample of user/behavior flow using Firebase analytics?
    Any idea how to capture and upload to Firebase? Thanks.

  • Ashutosh Tripathi

    Hi, Ravi..Great Tutorial..
    Can you please give a tutorial on how to integrate paytm…it would be great Thanks

  • susanto

    sir .. please help me ..
    i donot set any code in array store…………………….

    #include

    #include

    using namespace std;

    int main()

    {

    // Variable Declaration

    int a;

    // Get Input Value

    cout<>a;

    //for Loop Block

    for (int counter = 1; counter <= a; counter++)

    {

    cout<<"Execute "<<counter<<" time"<<endl;

    }

    // Wait For Output Screen

    getch();

    return 0;

    }

    #include

    #include

    #include

    #include

    void main()

    {

    char c,fname[10];

    ofstream out;

    cout<>fname;

    out.open(fname);

    cout<<"Enter contents to store in file (Enter # at end):n";

    while((c=getchar())!='#')

    {

    out<<c;

    }

    out.close();

    getch();

    }

  • Mohammad

    Nice tutorial and we are waiting a wonderful article form you πŸ™‚ again thank you so much

  • Ervan Prastyanto

    Great, Ravi can you share tutorial about Deep Linking, Dynamic Link, and App Indexing thx before πŸ˜€

    • Shubham Agarwal

      Yeah that i would love to read it. @ravi8x:disqus

  • ARASHI Funsho

    Hi Ravi.. Great Tutorials you’ve got. Can you please do a tutorial on Android Chat app/sending push notifications using Smack Library (XMPP). Thanks

    • ashwani Janu

      Yeah that one I would love too.. Thanks @ravi8x:disqus for sharing these tuts, always helpful.

  • ‫Ψ₯Ω„ΩŠΩˆΨ― Ω†Ψ¬ΩˆΨΊΩˆΩ†Ψ§β€¬β€Ž

    Thanks for the Tutorial but my app did not run because the Google Play Services in my Emulator is out of date..I have tried everything thats has been said in almost all chats and tutorial but i haven’t found any solution to that.

  • vishal gadhiya

    Hello ravi sir,

  • vishal gadhiya

    Hello ravisir

  • vishal gadhiya

    Hello ravi sir,

    I implement firebase analytics, so it working fine and generate log event in debug console but, this log event can’t upload on firebase console. i also waiting 3 to 4 days but no any recode on firebase console, below is my debug log,

    09-14 19:25:34.864 V/FA ( 4934): Activity resumed, time: 6013674
    09-14 19:25:36.994 W/FA ( 4934): Value is too long; discarded. Value kind,
    name, value length: param, item_id, 38
    09-14 19:25:36.994 D/FA ( 4934): Logging event (FE): select_content, Bundle
    [{_o=app, _ev=item_id, item_name=MoistAirActivity, content_type=Navigation Menu,
    _err=4}]
    09-14 19:25:36.994 V/FA ( 4934): Using measurement service
    09-14 19:25:36.994 V/FA ( 4934): Connecting to remote service
    09-14 19:25:36.994 D/FA ( 4934): Setting app measurement enabled (FE): true

    09-14 19:25:36.994 V/FA ( 4934): Setting measurementEnabled: true
    09-14 19:25:36.994 V/FA ( 4934): Using measurement service
    09-14 19:25:36.994 V/FA ( 4934): Connection attempt already in progress
    09-14 19:25:37.254 D/FA ( 4934): Connected to remote service
    09-14 19:25:37.254 V/FA ( 4934): Processing queued up service tasks: 2
    09-14 19:25:37.254 E/FA ( 4934): Task exception on worker thread: java.lang
    .IllegalStateException: FirebaseApp with name [DEFAULT] doesn’t exist. : com.goo
    gle.android.gms.measurement.internal.zzt.zzEd(Unknown Source)
    09-14 19:25:37.254 E/FA ( 4934): Task exception on worker thread: java.lang
    .IllegalStateException: FirebaseApp with name [DEFAULT] doesn’t exist. : com.goo
    gle.android.gms.measurement.internal.zzt.zzEd(Unknown Source)
    09-14 19:25:42.254 V/FA ( 4934): Inactivity, disconnecting from AppMeasurem
    entService

    Please give replay ASAP.

    Thanks.

  • Vishal G

    Hello ravi sir,

    I implement firebase analytics in my app, its working fine in my debug log but,this log event can’t upload this data on firebase console. my debug log is :

    09-14 19:25:34.864 V/FA ( 4934): Activity resumed, time: 6013674
    09-14 19:25:36.994 W/FA ( 4934): Value is too long; discarded. Value kind,
    name, value length: param, item_id, 38
    09-14 19:25:36.994 D/FA ( 4934): Logging event (FE): select_content, Bundle
    [{_o=app, _ev=item_id, item_name=MoistAirActivity, content_type=Navigation Menu,
    _err=4}]
    09-14 19:25:36.994 V/FA ( 4934): Using measurement service
    09-14 19:25:36.994 V/FA ( 4934): Connecting to remote service
    09-14 19:25:36.994 D/FA ( 4934): Setting app measurement enabled (FE): true

    09-14 19:25:36.994 V/FA ( 4934): Setting measurementEnabled: true
    09-14 19:25:36.994 V/FA ( 4934): Using measurement service
    09-14 19:25:36.994 V/FA ( 4934): Connection attempt already in progress
    09-14 19:25:37.254 D/FA ( 4934): Connected to remote service
    09-14 19:25:37.254 V/FA ( 4934): Processing queued up service tasks: 2
    09-14 19:25:37.254 E/FA ( 4934): Task exception on worker thread: java.lang
    .IllegalStateException: FirebaseApp with name [DEFAULT] doesn’t exist. : com.goo
    gle.android.gms.measurement.internal.zzt.zzEd(Unknown Source)
    09-14 19:25:37.254 E/FA ( 4934): Task exception on worker thread: java.lang
    .IllegalStateException: FirebaseApp with name [DEFAULT] doesn’t exist. : com.goo
    gle.android.gms.measurement.internal.zzt.zzEd(Unknown Source)
    09-14 19:25:42.254 V/FA ( 4934): Inactivity, disconnecting from AppMeasurem
    entService

    Please help me whats wrong with me??

  • Rahul kishan

    Note: You might not be able to see the changes and reports right away but within 24 hours.
    how can i achieve faster ?

  • Nimesh Chaturvedi
    • It could be because of multiple reasons. Search for ‘Firebase Failed to get Instance Id – analytics’ and see if any answers solve your problem.

  • Nikhil

    Hello Ravi.
    I want to know what happen when my app downloaded by more than 100 users.

  • Joan Wangu

    hello Ravi. Please share a tutorial about deep links and deferred deep links in android

  • Sahil Malhotra

    Hello sir
    ek doubt tha
    My app has video lectures so how can i use this to see which user stayed at which lecture and for how long?
    Is there a way out through this ?
    Please do respond.
    Thanks πŸ™‚

  • Nikhil Waghaye

    Which comments are coming in app? I am confused to check the comments in app.