Google Analytics Android Tutorial [For V4]

Please follow and like us:

android google analytic example

Google Analytics Android Tutorial/Example

Google analytics is a free and best analytics service for tracks and reports your websites traffic. Google analytics provides cool analytical tools for SEO(Search Engine Optimization) and very helpful to measure progress of your website. So we are going to explain Google Analytics Android Tutorial.

Why Google Analytics for Your Mobile Application ?

We mostly heard Google analytics for websites, but Google analytics also provide SDK(Software Development Kit) for integrating Google Analytics in Android application.

With the help of android Google analytics example, you can easily integrate it in your application and track user’s activity.

Features of Google Analytics in Android

There are too many powerful tools for tracking user’s activity like Mixpanel, Flurry, Clicky, Kissmetrics etc. but none of them are totally free and providing features like Google analytics provides. That’s why we came up with Android Google Analytics Tutorial, so you can easily integrate Android Google Analytics in your app.

Android Google Analytics v4 Cool Features

  • Absolutely Free Tool
  • Real Time Reporting of On line users from world wide.
  • Crash and Exception Reporting
  • Cross device and platform measurement.
  • Geo Tracking
  • Event Tracking
  • Advertising and Campaign Performance
  • Analysis and Testing
  • Audience Characteristics and Behavior
  • Data Collection and Management
  • Product Integrations(AdWords, Google Display Network, Google+, Wildfire, etc.)
  • Sales and Conversions
  • Site and App Performance

There are so many features of Google analytics, you can check it here

Integrating Android Google Analytics v4 Example step by step

Get Tracking ID for Android Google analytics [Tutorial]

  1. Login into your Google Analytics using your gmail account
  2.  Now Select Admin Tab in your account.
  3.  Open dropdown name “ACCOUNT”, click on Create new account or select the property from already created.
  4.  Select Mobile App option in form.
  5.  Add Account & App Name
  6.  Select Category according to your app
  7.  Modify Reproting time zone according your country.
  8.  Click on “Get Tracking ID”
  9.  In next screen you will get android Google analytics tracking ID.

Tracking ID’s format will be like this: UA-XXXXXXXX-X

Add following dependencies in your app’s build.gradle file for android google analytics example

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

 

In res folder, create new folder “xml”, then add “global_tracker.xml” file inside that folder

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <!-- The application name. Defaults to name specified for the application label -->
    <string name="ga_appName">Awesome Status</string>

    <!-- The application version. Defaults to android:versionName specified in the AndroidManifest.xml -->
    <string name="ga_appVersion">1.0</string>

    <!-- This will End current session if app sleeps for a period of time -->
    <integer name="ga_sessionTimeout">300</integer>

    <!-- This will Enable automatic Activity measurement -->
    <bool name="ga_autoActivityTracking">true</bool>

    <!-- The property id associated with this analytics tracker -->
    <string name="ga_trackingId">UA-67845537-1</string>

    <string name="ga_sampleFrequency">100.0</string>

    <!-- This will Enable reporting exceptions -->
    <bool name="ga_reportUncaughtExceptions">true</bool>

    <!-- For giving unique name to any activity -->
    <screenName name="com.nkdroid.android.googleanalytics.demo.SampleActivity">Sample Activity</screenName>

</resources>

Your AndroidMainifest.xml file will looks like here for android google analytics tutorial

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

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

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".MainActivity" android:label="@string/title_activity_main"></activity>

        <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />

        <meta-data android:name="com.google.android.gms.analytics.globalConfigResource" android:resource="@xml/global_tracker" />

        <!-- This is Optionally, This will register AnalyticsReceiver and AnalyticsService to support background dispatching on devices who have no google play. -->
        <receiver android:name="com.google.android.gms.analytics.AnalyticsReceiver" android:enabled="true">
            <intent-filter>
                <action android:name="com.google.android.gms.analytics.ANALYTICS_DISPATCH" />
            </intent-filter>
        </receiver>

        <service android:name="com.google.android.gms.analytics.AnalyticsService" android:enabled="true" android:exported="false" />

        <!-- This is Optionally, This will register CampaignTrackingReceiver and CampaignTrackingService to enable installation campaign reporting for your app -->
        <receiver android:name="com.google.android.gms.analytics.CampaignTrackingReceiver" android:exported="true">
            <intent-filter>
                <action android:name="com.android.vending.INSTALL_REFERRER" />
            </intent-filter>
        </receiver>

        <service android:name="com.google.android.gms.analytics.CampaignTrackingService" />

        <activity android:name=".SampleActivity" android:label="@string/title_activity_sample"></activity>
    </application>

</manifest>

style.xml in res->values folder will be looks like for android google analytics

<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="AppTheme" parent="AppTheme.Base">
    </style>
<style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">

        <item name="colorPrimary">@color/primaryColor</item>
        <item name="colorPrimaryDark">@color/primaryColorDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:textColorPrimary">@color/colorTextPrimary</item>
        <item name="android:textColorSecondary">@color/colorTextSecondary</item>

    </style>
</resources>

color.xml in res->values folder will be looks like for android google analytics demo

<?xml version="1.0" encoding="utf-8"?>
<resources>

<color name="primaryColor">#2196F3</color>
<color name="primaryColorDark">#1976D2</color>
<color name="colorAccent">#FF4081</color>
<color name="colorTextPrimary">#212121</color>
<color name="colorTextSecondary">#727272</color>
</resources>

add application class “Myapplication.java” for initialize Google analytics

package com.nkdroid.android.googleanalytics.demo.app;

import android.app.Application;

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

/**
 * Created by nirav on 20/09/15.
 */
public class Myapplication extends Application {
    public static final String TAG = Myapplication.class
            .getSimpleName();

    private static Myapplication mInstance;

    public static synchronized Myapplication getInstance() {
        return mInstance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;

        AnalyticsTrackersClass.initialize(this);
        AnalyticsTrackersClass.getInstance().get(AnalyticsTrackersClass.Target.APP);
    }

    public synchronized Tracker getGoogleAnalyticsTracker() {
        AnalyticsTrackersClass analyticsTrackersClass = AnalyticsTrackersClass.getInstance();
        return analyticsTrackersClass.get(AnalyticsTrackersClass.Target.APP);
    }


    public void trackScreenView(String screenName) {
        Tracker t = getGoogleAnalyticsTracker();

        // Set screen name.
        t.setScreenName(screenName);

        // Send a screen view.
        t.send(new HitBuilders.ScreenViewBuilder().build());

        GoogleAnalytics.getInstance(this).dispatchLocalHits();
    }


    public void trackException(Exception e) {
        if (e != null) {
            Tracker t = getGoogleAnalyticsTracker();

            t.send(new HitBuilders.ExceptionBuilder()
                            .setDescription(
                                    new StandardExceptionParser(this, null)
                                            .getDescription(Thread.currentThread().getName(), e))
                            .setFatal(false)
                            .build()
            );
        }
    }

    public void trackEvent(String category, String action, String label) {
        Tracker t = getGoogleAnalyticsTracker();

        // Build and send an Event.
        t.send(new HitBuilders.EventBuilder().setCategory(category).setAction(action).setLabel(label).build());
    }

}

Also add AnalyticsTrackerClass.java class for android Google analytics tracking

package com.nkdroid.android.googleanalytics.demo.app;

import android.content.Context;

import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.Tracker;
import com.nkdroid.android.googleanalytics.demo.R;

import java.util.HashMap;
import java.util.Map;


public final class AnalyticsTrackersClass {

    private static AnalyticsTrackersClass sInstance;
    private final Map<Target, Tracker> mTrackers = new HashMap<Target, Tracker>();
    private final Context mContext;

    private AnalyticsTrackersClass(Context context) {
        mContext = context.getApplicationContext();
    }

    public static synchronized void initialize(Context context) {
        if (sInstance != null) {
            throw new IllegalStateException("Extra call to initialize analytics trackers");
        }

        sInstance = new AnalyticsTrackersClass(context);
    }

    public static synchronized AnalyticsTrackersClass getInstance() {
        if (sInstance == null) {
            throw new IllegalStateException("Call initialize() before getInstance()");
        }

        return sInstance;
    }

    public synchronized Tracker get(Target target) {
        if (!mTrackers.containsKey(target)) {
            Tracker tracker;
            switch (target) {
                case APP:
                    tracker = GoogleAnalytics.getInstance(mContext).newTracker(R.xml.global_tracker);
                    break;
                default:
                    throw new IllegalArgumentException("Unhandled analytics target " + target);
            }
            mTrackers.put(target, tracker);
        }

        return mTrackers.get(target);
    }

    public enum Target {
        APP,
        // Add more trackers here if you need, and update the code in #get(Target) below
    }
}

activity_main.xml contains buttons for different kinds of tracking for android google analytics…

<LinearLayout 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:orientation="vertical"
    tools:context="com.nkdroid.android.googleanalytics.demo.MainActivity">

    <include layout="@layout/app_bar" />

    <TextView
        android:id="@+id/btnActivityTracking"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:background="@color/primaryColorDark"
        android:gravity="center"
        android:padding="20dp"
        android:text="Activity Tracking"
        android:textColor="#fff"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/btnFragmentTracking"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:background="@color/primaryColorDark"
        android:gravity="center"
        android:padding="20dp"
        android:text="Fragment Tracking"
        android:textColor="#fff"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/btnEventTracking"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:background="@color/primaryColorDark"
        android:gravity="center"
        android:padding="20dp"
        android:text="Event Tracking"
        android:textColor="#fff"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/btnExceptionTracking"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:background="@color/primaryColorDark"
        android:gravity="center"
        android:padding="20dp"
        android:text="Exception Tracking"
        android:textColor="#fff"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/btnCrashTracking"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:background="@color/primaryColorDark"
        android:gravity="center"
        android:padding="20dp"
        android:text="App Crash Tracking"
        android:textColor="#fff"
        android:textSize="18sp" />


    <FrameLayout
        android:id="@+id/main_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

MainActivity.java contains the main logic of tracking android Google analytics

package com.nkdroid.android.googleanalytics.demo;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.nkdroid.android.googleanalytics.demo.app.Myapplication;


public class MainActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private TextView btnActivityTracking, btnFragmentTracking, btnEventTracking, btnExceptionTracking, btnCrashTracking;

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

        setToolbar();
        initView();

    }

    private void setToolbar() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        if (toolbar != null) {
            toolbar.setTitle("Google Analytics Demo");
            setSupportActionBar(toolbar);
        }
    }

    private void initView() {
        btnActivityTracking = (TextView) findViewById(R.id.btnActivityTracking);
        btnFragmentTracking = (TextView) findViewById(R.id.btnFragmentTracking);
        btnEventTracking = (TextView) findViewById(R.id.btnEventTracking);
        btnExceptionTracking = (TextView) findViewById(R.id.btnExceptionTracking);
        btnCrashTracking = (TextView) findViewById(R.id.btnCrashTracking);

        btnActivityTracking.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, SampleActivity.class);
                startActivity(intent);
            }
        });

        btnFragmentTracking.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                FragmentManager fragmentManager = getSupportFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                SampleFragment sampleFragment = SampleFragment.newInstance();
                fragmentTransaction.replace(R.id.main_container, sampleFragment);
                fragmentTransaction.commit();
            }
        });

        btnEventTracking.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // category, action, label
                Myapplication.getInstance().trackEvent("Event Tracking", "Event Fire", "Sample Event");

                Toast.makeText(getApplicationContext(), "Check event tracking on analytic dashboard", Toast.LENGTH_LONG).show();
            }
        });

        btnExceptionTracking.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    String name = null;
                    if (name.equals("Android Google Analytics Demo")) {
                        //throw null pointer exception
                    }
                } catch (Exception e) {
                    // Tracking exception
                    Myapplication.getInstance().trackException(e);

                    Toast.makeText(getApplicationContext(), "Exception Fire", Toast.LENGTH_LONG).show();


                }
            }
        });

        btnCrashTracking.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getApplicationContext(), "App Crash Fire", Toast.LENGTH_LONG).show();
                throw new RuntimeException("This is a crash");
            }
        });
    }


}

There are three ways to track android google analytics for any android app’s screen 

1> by declaring following things in global_tracker.xml(this will automatically track all activities of app) for android google analytics

<!-- This will Enable automatic Activity measurement -->
    <bool name="ga_autoActivityTracking">true</bool>

2> adding unique screen name with full package name in global_tracker.xml(this will helpful when we need unique name to any screen) for android google analytics

<!-- For giving unique name to any activity -->
    <screenName name="com.nkdroid.android.googleanalytics.demo.SampleActivity">Sample Activity</screenName>

3> add manually in each screen class in onResume() method for android google analytics

// for tracking manual 
        Myapplication.getInstance().trackScreenView("Sample Fragment");

android google analytics v4 step by step example

Hope, you will like our integrating android google analytics example step by step process. if you have any query regarding implementing android google analytics tutorial in android app then comment bellow.

Download Google Analytics Android Tutorial

nirav kalola