Google Analytics Android Integration using Android Studio

Did you ever wanted to track your users in real time? Did you ever wondered how many people are using your app right now and in what activity/screen they are currently in,which country uses your app the most? Here is the easiest and free service to track all those in an easy manner – Google Analytics. Google Analytics Android is a great way to look at how the users are interacting with your App or Website. google analytics android

Google Analytics for Android helps to know about real time user count, geo tracking, Audience Acquisition, Crash Reports, App traffic Alerts in case of spike in traffic, etc. It also gives info about the Mobile Devices used by user, info about Button Clicks, info about Crashes and Exceptions, Total Number of New users and Total Active Users Per day/ Week/ Month and much more. In this Article, Let us work through this easy and exciting tutorial and simply Integrate Google Analytics in our Android app!

The below image shows the Real time Tracking by using Google Analytics in one of the app created by us.

google analytics android Traffic Eg

In this tutorial we will work on the following important features of Google Analytics Android:

  1. Activity/Screen Tracking
  2. Fragment Tracking
  3. Event Tracking
  4. Exception Tracking
  5. Crash Tracking

The complete code can be downloaded from the link below:


To utilize the features of Google Analytics we need a Tracking ID from Google. So let us start by creating it.

1.    Creating Analytics Property and Generating Tracking ID:

To create a new Analytics Property, Sign in into Google Analytics Account using your Google Account.

Select Admin Tab and click on Account > Create New Account. In case if you already have a desired account select that and Create a Property.google analytics android properties configuration

Select Mobile app tab and give the App Name.

Click on Get Tracking ID Button below.

Now you will get a tracking ID which will be of the form UA-XXXXXXXX-X

2. Creating Google Analytics Android Tutorial Project and Adding Required Code:

Now Let us create the project. Open Android Studio and Click File > Close All Projects.

Now click Create New Android Studio Project and hit Next . Here I named my Project as Google Analytics Android Tutorial.

Fill all the required details. Choose Blank activity in case of Android Studio version <1.4 version (or) Empty Activity in case of Android Studio >1.4 version.

For more reference about creating a project refer to the following article:

Getting Started with Android Studio by creating your first Project

a. Adding Required Permissions:

To Integrate Analytics into Android Studio we need to add the following required permissions to our Google Analytics Android Tutorial‘s Manifest File:

b. Adding Dependencies and Plugins:

To make Analytics work, we need to add the dependencies and Plugins to our build.gradle file in Android Studio.

First, set the project to Android View. Select Project’s build.gradle and add the following piece of code:

Project’s build.gradle file is also considered as Top Level build.gradle file. Make sure you added the above code in Project’s build.gradle.

Now open app’s build.gradle file and add the following code:

In Dependencies section of app’s build.gradle file, add the following code:

Note: Google always updates the google services, play services analytics version. While the above code works, in order to make sure you always use the latest code, refer to the code in this link.

Now the app’s build.gradle will look like the following:

Now we need to add google-services.json file in our project in order to add analytics. To get the file, click this link and Give your app name and project name.google analytics android getting json file

Now Click on Choose and Configure Services.

Here you can add the services such as Analytics, Google + Integration, Google Cloud Messaging Services etc. Since this tutorial is focused on Google Analytics, let us just configure the file for Google Analytics.

Now click on Analytics logo and fill the details below. You need a Google Analytics in order to configure the service below. Since we covered this in our first step, let us select the property created in our analytics. Now click on Enable Analytics Service.

Now scroll down and Click on Generate Configuration Files.

Now you can download the json file. Copy the file and Paste it in the app folder of your project. It will be generally:

C:\Users\<USERNAME>\AndroidStudioProjects\GoogleAnalyticsAndroidTutorial\app

c. Creating and Configuring XML file:

Now create an xml file named analytics_tracker.xml in res > xml folder of our Google Analytics Android Tutorial Project to use it as a custom Analytics Configuration File. If xml folder doesnot exist, create a folder named xml. Now add the following code in the newly created analytics_tracker.xml file:

Note: Make  sure you replace the tracking Id in the code above with your tracking Id generated in the Step 1. Otherwise, tracking Will NOT work.

d. Adding required additional String Resources:

Before going any further, let us add required additional String resource files.

e. Creating a Class which extends Application:

We will now add a Class with name GoogleAnalyticsApplication.java to our Google Analytics Android Tutorial Project which will extend Application Class from android.app package.

We will now add the following code to our class:

We now open AndroidManifest.xml and add application name as follows:

Now our Manifest file will now look as follows:

f. Modifying activity_main.xml

First we will modify our activity_main.xml by adding the following code:

 

3. Tracking an Activity:

We will now discuss about how to track an Activity using Google Analytics by implementing the code in our MainActivity.java.

To track Activities/Screens, we use ScreenViewBuilder() method from HitBuilders Class to send Screen to Google Analytics Android.

Open MainActivity.java and add the Tracker variable:

Now add this piece of code in onCreate() method:

Now we need to override onResume() method to declare the following code:

We will also wire up the buttons in our MainActivity.java and add the code to our NextScreen Button Variable so that it can Start Next Activity/Screen. Now the MainActivity.java will look as follows:

To track Next Screen also, create NextScreen.java and add the following code:

 

Now you can successfully run the app and switch between Activities. You also can successfully track your app in Google Analytics Dashboard.

Important Note: It will usually takes 1-3 minutes for Google Analytics to track your Activity/screen in Real time.

The following image shows the real time Tracking of this app with the screen Name main screen:google analytics android tutorial tracking

4. Tracking A Fragment :

Tracking a Fragment is very similar to Tracking an Activity. Here, We use the same method, i.e., ScreenViewBuilder() method from HitBuilders class in our Fragment’s onResume() method to track the fragment in Google Analytics Android. Let us now create a Fragment and Add it to our MainActivity. Let us name the Fragment class as FragmentDemo.java and add the following code to it:

The above code inflates my_fragment.xml file. Now open my_fragment.xml file and add the following code to it:

Since we already added a Frame Layout in our activity_main.xml file, the above fragment can be inflated in our activity_main.xml file.

To inflate and remove this Fragment in our MainActivity.xml file, we will add the following code to our Fragment Button variable bFragment in our onCreate() method:

5. Event Tracking:

Event Tracking is used to Track any events such as Button Clicks, Downloads, Item Purchases, Tracking of any items in a Game such as Level Completion, in-app Purchases, Power ups, etc.

To track an Event, we use EventBuilder() method from HitBuilder class to Track Events in Google Analytics.

In this Tutorial, Let us suppose that we want to Track the Purchase of a Movie Ticket. Let us Register that event in our Google Analytics Account from our Google Analytics Android Tutorial App.

Here is the code we need to add in our Main Activity’s onCreate Method so that when user presses button, Event will be registered:

6. Crashes and Exception Tracking

Exception Tracking is used to track Crashes and Exceptions. Any uncaught Exception can be sent to Google Analytics by using 2 methods.

  1. Track the uncaught Exceptions automatically by adding the following code in xml file:

<bool name=”ga_reportUncaughtExceptions”>true</bool>

  1. This is an advanced implementation to track the uncaught Exceptions if you are not using Method 1. To implement this advanced config, use the following code:

    Method 1 is is more easy to configure and is preferrable.

    Additional Configuration:

    In order to get and send more description of the Exception we can use the following code:

    Here in this Google Analytics Android Tutorial, we created some situations where the app will generate Exception and Crash. Let us see them Individually.

a. Exception Tracking

Here we will configure the Exception button so that an Exception will be created whenever user presses Exception Tracking button. Let us create an Array out of Bounds Exception by declaring the following code:

Here we used ExceptionBuilder() method from HitBuilders class to send the Exception to Google Analytics.

Note: Exceptions and Crashes usually take upto 24 hours to get registered in Google Analytics Dashboard. Google Analytics currently does not support Real time Crash and Exception tracking.

b. Crash Tracking:

We configure Crash Tracking Button so that when user presses the button, a toast message will be displayed and the app will crash after 1.5 seconds. Here we created crash by throwing null pointer exception

These are the most commonly used features of Google Analytics. Google offers a lot more features via Google Analytics. Refer to Documentation for integrating more features.

Vamsi Tallapudi
Connect Via

Vamsi Tallapudi

Founder and Author at Code Refer
Android Dev, Tech Enthusiast and Blogger. Ever since my first basic android app has reached lakhs of users, I've found myself in love with Android Development :). While my primary passion is coding, during my free time, you can find me blogging, travelling or on Facebook 🙂
Vamsi Tallapudi
Connect Via

Vamsi Tallapudi

Android Dev, Tech Enthusiast and Blogger. Ever since my first basic android app has reached lakhs of users, I've found myself in love with Android Development :). While my primary passion is coding, during my free time, you can find me blogging, travelling or on Facebook :)

You may also like...

  • ratansingh

    Nice

  • Syeda zunairah

    Hi Very nice tutorial Thanks. I had successfully added in the Google Analytics in my app but I am facing the issue in real time tracking, no right now users are appearing but after few hours or a day it appeared on dash board. I just want to track them on real time too. Please guide me.