Google Analytics Android Integration using Android Studio

2
11
google analytics android

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
[widget id=”text-3″]

The complete code can be downloaded from the link below:
[wpdm_package id=’762′] 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:

<uses-permission android:name = “android.permission.INTERNET”/>
<uses-permission android:name = “android.permission.ACCESS_NETWORK_STATE”/>

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:

classpath 'com.google.gms:google-services:1.4.0-beta3'

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:

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

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

compile 'com.google.android.gms:play-services-analytics:8.1.0'

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:

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

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"

    defaultConfig {
        applicationId "com.coderefer.googleanalyticsandroidtutorial"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.0.1'
    compile 'com.google.android.gms:play-services-analytics:8.1.0'
    compile 'com.android.support:design:23.0.1'
}

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.

[widget id=”text-3″]

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:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="ga_trackingId">UA-XXXXXXXX-X</string>
    <bool name="ga_reportUncaughtExceptions">true</bool>

</resources>

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.

<string name="app_name">Google Analytics Android Tutorial</string>
    <string name="title_activity_next_screen">Next Screen</string>
    <string name="my_fragment">This is a Fragment! Tap Fragment Button again to remove this Fragment from this Activity</string>
    <string name="categoryId">Purchase</string>
    <string name="actionId">Buy Tickets</string>
    <string name="labelId">Buy Tickets Button Pressed!</string>

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:

package com.coderefer.googleanalyticsandroidtutorial;

import android.app.Application;

import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.Tracker;

/**
 * Created by Vamsi Tallapudi on 24-Oct-15.
 */
public class GoogleAnalyticsApplication extends Application {

    private Tracker mTracker;

    /**
     * Gets the default {@link Tracker} for this {@link Application}.
     * @return tracker
     */
    synchronized public Tracker getDefaultTracker() {
        if (mTracker == null) {
            GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
            // Setting mTracker to Analytics Tracker declared in our xml Folder
            mTracker = analytics.newTracker(R.xml.analytics_tracker);
        }
        return mTracker;
    }

}

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

android:name=".GoogleAnalyticsApplication"

Now our Manifest file will now look as follows:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.coderefer.googleanalyticsandroidtutorial" >

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

    <application
        android:name=".GoogleAnalyticsApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity android:name=".MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".NextScreen"
            android:label="@string/title_activity_next_screen"
            android:parentActivityName=".MainActivity"
            android:theme="@style/AppTheme.NoActionBar" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.coderefer.googleanalyticsandroidtutorial.MainActivity" />
        </activity>
    </application>

</manifest>

f. Modifying activity_main.xml

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

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#400000FA"
    android:paddingTop="@dimen/activity_horizontal_margin"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_alignParentTop="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_above="@+id/container"
        android:weightSum="5">

        <Button
            android:id="@+id/bNextScreen"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center_horizontal"
            android:layout_margin="20dp"
            android:layout_weight="1"
            android:background="#80ffffff"
            android:text="Next Screen (Activity Tracking)"
            android:textColor="#FF4081" />

        <Button
            android:id="@+id/bFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center_horizontal"
            android:layout_margin="20dp"
            android:layout_weight="1"
            android:background="#80ffffff"
            android:text="Fragment Tracking"
            android:textColor="#FF4081" />

        <Button
            android:id="@+id/bEvent"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center_horizontal"
            android:layout_margin="20dp"
            android:layout_weight="1"
            android:background="#80ffffff"
            android:text="Event Tracking"
            android:textColor="#FF4081" />

        <Button
            android:id="@+id/bException"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center_horizontal"
            android:layout_margin="20dp"
            android:layout_weight="1"
            android:background="#80ffffff"
            android:text="Exception Tracking"
            android:textColor="#FF4081" />

        <Button
            android:id="@+id/bCrashApp"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center_horizontal"
            android:layout_margin="20dp"
            android:layout_weight="1"
            android:background="#80ffffff"
            android:text="Crash Tracking"
            android:textColor="#FF4081" />

   </LinearLayout>


    <FrameLayout
        android:padding="10dp"
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true" />

</RelativeLayout>

 

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.

[widget id=”text-3″]

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:

Private Tracker mTracker

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

//Analytics Integration
// Obtain the shared Tracker instance.
GoogleAnalyticsApplication application = (GoogleAnalyticsApplication) getApplication();
mTracker = application.getDefaultTracker();

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

    @Override
    protected void onResume() {
        super.onResume();
        mTracker.setScreenName(“Main Screen”);
        mTracker.send(new HitBuilders.ScreenViewBuilder().build());
    }

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:

package com.coderefer.googleanalyticsandroidtutorial;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.StandardExceptionParser;
import com.google.android.gms.analytics.Tracker;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();
    private Tracker mTracker;
    String name = new String("Main Screen");
    static Boolean toggle = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Analytics Integration
        // Obtain the shared Tracker instance.
        GoogleAnalyticsApplication application = (GoogleAnalyticsApplication) getApplication();
        mTracker = application.getDefaultTracker();

        Button bNextScreen = (Button) findViewById(R.id.bNextScreen);
        Button bFragment = (Button) findViewById(R.id.bFragment);
        Button bEvent = (Button) findViewById(R.id.bEvent);
        Button bException = (Button) findViewById(R.id.bException);
        Button bCrashApp = (Button) findViewById(R.id.bCrashApp);

        //Starts Next Activity/Screen
        bNextScreen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(MainActivity.this, NextScreen.class);
                startActivity(i);
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG, "Setting screen name: " + name);
        //using tracker variable to set Screen Name
        mTracker.setScreenName(name);
        //sending the screen to analytics using ScreenViewBuilder() method
        mTracker.send(new HitBuilders.ScreenViewBuilder().build());
    }
}

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

package com.coderefer.googleanalyticsandroidtutorial;

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.util.Log;
import android.view.View;

import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;

public class NextScreen extends AppCompatActivity {

    private static final String TAG = NextScreen.class.getSimpleName();
    private Tracker mTracker;
    private String name = "Next Screen";

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

        //Analytics Integration
        // Obtain the shared Tracker instance.
        GoogleAnalyticsApplication application = (GoogleAnalyticsApplication) getApplication();
        mTracker = application.getDefaultTracker();

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG, "Setting screen name: " + name);
        mTracker.setScreenName(name);
        mTracker.send(new HitBuilders.ScreenViewBuilder().build());
    }

}

 

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:

package com.coderefer.googleanalyticsandroidtutorial;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;

/**
 * Created by Vamsi Tallapudi on 24-Oct-15.
 */
public class FragmentDemo extends Fragment {

    private static final String TAG = FragmentDemo.class.getSimpleName();
    private Tracker mTracker;
    String name = new String("Fragment Demo");

    public FragmentDemo(){

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        GoogleAnalyticsApplication application = (GoogleAnalyticsApplication) getActivity().getApplication();
        mTracker = application.getDefaultTracker();

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.my_fragment, container, false);
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.i(TAG, "Setting screen name: " + name);
        mTracker.setScreenName(name);
        mTracker.send(new HitBuilders.ScreenViewBuilder().build());

    }

}

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

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.coderefer.googleanalyticsandroidtutorial.FragmentDemo">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/my_fragment"
        android:background="@color/colorAccent"
        android:textColor="#ffffff"
        android:textAlignment="center"
        android:gravity="center"
        android:textSize="15dp"
        android:layout_margin="20dp"/>

</FrameLayout>

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:

  bFragment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                FragmentManager fragmentManager = getSupportFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                Fragment myFragment = (Fragment) fragmentManager.findFragmentByTag("TAG_FRAGMENT");
                if (myFragment == null) {

                    myFragment = new FragmentDemo();

                    fragmentTransaction.replace(R.id.container, myFragment, "TAG_FRAGMENT");
                    fragmentTransaction.commit();

                } else {
                    fragmentTransaction.remove(myFragment).commit();

                }

            }
        });

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:

bEvent.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        // Get tracker.
        Tracker t = ((GoogleAnalyticsApplication) getApplication()).getDefaultTracker();

        // Build and send an Event.
        t.send(new HitBuilders.EventBuilder()
                .setCategory(getString(R.string.categoryId))
                .setAction(getString(R.string.actionId))
                .setLabel(getString(R.string.labelId))
                .build());
        Toast.makeText(MainActivity.this, "Event is recorded. Check Google Analytics!", Toast.LENGTH_LONG).show();
    }
}); 

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:
    UncaughtExceptionHandler myHandler = new ExceptionReporter(
        myTracker,                                        // Currently used Tracker.
        Thread.getDefaultUncaughtExceptionHandler(),      // Current default uncaught exception handler.
        context);                                         // Context of the application.
    
    // Make myHandler the new default uncaught exception handler.
    Thread.setDefaultUncaughtExceptionHandler(myHandler);
    

    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:

    catch (IOException e) {
    // Get tracker.
    Tracker t = ((AnalyticsSampleApp) getActivity().getApplication()).getTracker(
        TrackerName.APP_TRACKER);
    
      t.send(new HitBuilders.ExceptionBuilder()
          .setDescription(
              new StandardExceptionParser(this, null)
                  .getDescription(Thread.currentThread().getName(), e))
          .setFatal(false)
          .build()
      );
    
      ... // Display alert to user that high scores are currently unavailable.
    }
    

    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:

bException.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Exception e = null;

                try{
                    int num[]={1,2,3,4};
                    System.out.println(num[5]);
                }catch (Exception f){
                    e = f;
                }
                if( e != null){

                    Toast.makeText(MainActivity.this, "The Exception is: " + e, Toast.LENGTH_LONG).show();

                    Tracker t = ((GoogleAnalyticsApplication) getApplication()).getDefaultTracker();
                    t.send(new HitBuilders.ExceptionBuilder()
                            .setDescription(new StandardExceptionParser(MainActivity.this, null).getDescription(Thread.currentThread().getName(), e))
                            .setFatal(false)
                            .build());
                }



            }
        });

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

 bCrashApp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getApplicationContext(), "Get Ready for App Crash!", Toast.LENGTH_LONG).show();
                Runnable r = new Runnable() {
                    @Override
                    public void run() {
                        startCrash();

                    }
                    public void startCrash() {
                        //Manually throwing nullPointer Exception using throw keyword
                        throw null;
                    }

                };
                Handler h = new Handler();
                h.postDelayed(r, 1500);
            }
        });

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.

[widget id=”text-4″]

2
Leave a Reply

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
2 Comment authors
Syeda zunairahratansingh Recent comment authors

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
newest oldest most voted
Notify of
ratansingh
Guest
ratansingh

Nice

Syeda zunairah
Guest
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.