Tutorial : Quick Integration of Android Google Analytics API v4

10:08 PM 0 Comments



       Google Analytics API v4 for Android is powerful than the previous version of Analytics API v3 which is deprecated now. Google Analytics API offers wide verity of features such as you can keep track of your apps statistics - real time, events and much more.
The tutorial explores how to integrate API version 4 in an android app, many developers are still struggling with new API v4. Google Analytics API v4  is pre-defined under Google Play Services SDK. Now let's start with quick integration.
 Android Google Analytics API v4 tutorial



Prerequisites

·    Google Analytics Account
·    PROPERTY_ID - Create an App property ID & Add a new View
·    Google Play Services
·    Eclipse +Android SDK (or Android Studio)

Step 1

Setting up Google Play Services


Once you have completed the Analytics account procedures for app tracking, proceed to next step setting up Google play services. Follow the link to configure the Play services in your app.

Step 2

Prepare XML files


Make a new folder ‘xml’ in your project (right click on res > New > folder) Now you will have to create two xml files global_tracker.xml and ecommerce_tracker.xml (to create xml file -New > Android XML file)

ecommerce_tracker.xml 


<?xml version="1.0" encoding="utf-8"?>
<resources>
    <integer name="ga_sessionTimeout">60</integer>

    <string name="ga_trackingId">UA-XXXXX-X</string>
</resources>

If you observe the above file , ga_trackingId should be replaced with correct property id.

global_tracker.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <integer name="ga_sessionTimeout">300</integer>
    <bool name="ga_autoActivityTracking">true</bool>
    <screenName name="com.bigknol.SocialShare">
        Social Share Screen
    </screenName>
   <screenName name="com.bigknol.About">
        About App Screen
    </screenName>

    <string name="ga_trackingId">UA-XXXXX-X</string>
</resources>


As you can see, there two screen names are created under resource root. The screen names will be shown in Analytics real-time view and other metrics. The screen names are defined using package name with your activity class. moreover you can define screen names dynamically using a void method com.google.android.gms.analytics.Tracker.setScreenName(String screenName). We will try it next,

step 3

Prepare Permissions & Meta tag

Open up your AndroidManifest.xml file and add the following permissions, you can ignore it if you have successfully done Google play services integration.

Place permissions outside the application tag

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

Place meta tag as immediate child of application tag.

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

Step 4

Make an Analytics class

To create a class – right click on package > New > Class Name the class as Analytics
Remember : Do not make activity instead of class, because we going to make Application, Analytics class extends Application (android.app.Application)

Do not forget to import the following things
import com.google.android.gms.analytics.Logger;
import com.google.android.gms.analytics.Tracker;
import com.google.android.gms.analytics.GoogleAnalytics;
import android.app.Application;
import java.util.HashMap;

Analytics.java



package com.bigknol.analytics;

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

import android.app.Application;

import java.util.HashMap;

public class Analytics extends Application {

    private static final String PROPERTY_ID = "UA-XXXXX-X";

    public static int GENERAL_TRACKER = 0;

    public enum TrackerName {
        APP_TRACKER,
        GLOBAL_TRACKER,
        ECOMMERCE_TRACKER,
    }

    HashMap<TrackerName, Tracker> mTrackers = new HashMap<TrackerName, Tracker>();

    public Analytics() {
        super();
    }

    synchronized Tracker getTracker(TrackerName trackerId) {
        if (!mTrackers.containsKey(trackerId)) {

            GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
            analytics.getLogger().setLogLevel(Logger.LogLevel.VERBOSE);
            Tracker t = (trackerId == TrackerName.APP_TRACKER) ? analytics.newTracker(PROPERTY_ID)
                    : (trackerId == TrackerName.GLOBAL_TRACKER) ? analytics.newTracker(
                            R.xml.global_tracker)
                            : analytics.newTracker(R.xml.ecommerce_tracker);
            t.enableAdvertisingIdCollection(true);
            mTrackers.put(trackerId, t);
        }
        return mTrackers.get(trackerId);
    }
}

APP_TRACKER – it is specially designed for only in this app to keep track.
GLOBAL_TRACKER – Used by all apps from a company
ECOMMERCE_TRACKER – Tracker used all e-commerce transactions

Step 5 

Mark application entry – Manifest

Add Analytics as application name on Manifest entry as below :
<application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
        android:name=".Analytics">

Step 6

Invoke Analytics on Android Activity or ActionBarActivity

Time to use Analytics class, create a new activity called MainActivity
Create Tracker object to invoke Analytics Application like below :

Tracker t = ((Analytics) getApplication()).getTracker(

                    TrackerName.APP_TRACKER);

MainActivity.java

package com.bigknol.analytics;

import com.bigknol.analytics.Analytics.TrackerName;
import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Choreographer.FrameCallback;
import android.widget.Toast;

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try
{
  Tracker t = ((Analytics) getApplication()).getTracker(
          TrackerName.APP_TRACKER);

t.setScreenName("MyScreenName");

t.send(new HitBuilders.AppViewBuilder().build());
}
catch(Exception  e)
{
Toast.makeText(getApplicationContext(), "Error"+e.getMessage(), 1).show();
}
}
@Override
 protected void onStart() {
  // TODO Auto-generated method stub
  super.onStart();
  GoogleAnalytics.getInstance(this).reportActivityStart(this);
 }

 @Override
 protected void onStop() {
  // TODO Auto-generated method stub
  super.onStop();
  GoogleAnalytics.getInstance(this).reportActivityStop(this);
 }
}
Calling Tracker – ignore it if you are using activity instead of ActionBar, ActionBarActivity etc.
Tracker t = ((Analytics) getActivity().getApplication()).getTracker(
TrackerName.APP_TRACKER);

Final Manifest File:


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.bigknol.analytics"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="9"
        android:targetSdkVersion="21" />

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
        android:name=".Analytics">
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >

              <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Step 7
Run your project

Run app and open up the Analytics realtime -overview .. Done

Extra Tips for Google Analytics API v4 (Android)
if you are using Admob, or advertising feature you could enable special tracking feature for them. to enable call a tracker method

Tracker t = ((Analytics) getApplication()).getTracker(TrackerName.APP_TRACKER);
t.enableAdvertisingIdCollection(true);

Lint Warning 

You may encounter a lint warning quick use of – (hyphen) in Property ID. Add the following ignore case to avoid it.


<resources xmlns:tools="http://schemas.android.com/tools"
tools:ignore="TypographyDashes">

Hi Nikinmon SK i like to share my knowledge !