How to Integrate Google Analytics V4 in Android (Tracking Only)

How to Integrate Google Analytics V4 in Android (Tracking Only)

Recently, I was planning to integrate Google Analytics to my new app so I found out the Google has updated Google Analytics to version 4.

Before, the integration of EasyTracker (Google Analytics V3) is simple. I decided to go through V4 and see how I can implement a simple tracker in my app. Between the two versions, the implementation methods are slightly different.

In this short tutorial, I will let you see how I implemented a simple tracking in my app. There are many other features the API provides like app crash report, exceptions, etc that we will not cover here. In my next tutorial, I will go into details on how to implement most of the features the API provides.

Before we start, you should head to Google Analytics website, to register for any account if you do not have one already. The registration link is as shown in this link.

google analytics

You will register / create a new account if you have not done that yet. The registration is straight forward. With your Google account, you can equally login.

Click on the admin menu in the top navigation links

Thereafter, click on the Account drop-down. At the tail end, you will select create new account to proceed with the account form.

Follow the instructions to add relevant information in the input box provided. Click on the create button to create.

Now let move unto Google user guide page, you will get all the formation or answer to questions in mind about setting up Google Adsense in android.

Before you go further, we are going to create on android application. For this android example tutorial, I will use the following tools and environment.

Windows 7

Android Studio

Sony Xperia ZL

Min SDK 14

Target SDK 19

To create a new android application project, following the steps as stipulated below.

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: AndroidGoogleAnalytics

Package: com.inducesmile.androidgoogleanalytics

Keep other default selections.

Continue to click on next button until Finish button is active, then click on Finish Button

We are going to add Google Play Services in our project. If you are using Android Studio, open your build.gradle and add this line of code compile ‘com.google.android.gms:play-services:7.5.0’ . The image is as shown

googleanalytics

Since the use of Google Analytics requires in network call, we are going to add two permissions in our project Manifest file as below.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.inducesmile.henry.androidgoogleanalytics" >
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

We will go back to the Analytics SDK for Android page, click on the get configuration button. The configuration file provides service-specific information for your app. To get it, you must select an existing project for your app or create a new one. You’ll also need to provide a package name for your app.

The image of the page is as shown. Fill in the app name and other required information to download your application configuration file.

google analytics

Once you download the file (google-services.json), we will add it to app directory of our project, if you are using Android Studio as your development IDE. For those, using Eclispe, I will suggest, you check how to install Analytics SDK in android.

We will move forward to create a subclass of our application class. The class will contain a method that will return the tracker object which will track every Activity page in our app. The code for the class is as shown.

import android.app.Application;
import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.Logger;
import com.google.android.gms.analytics.Tracker;
import java.util.HashMap;
public class AnalyticsApplication extends Application {
    
    public enum TrackerName {
        APP_TRACKER,
        GLOBAL_TRACKER,
        E_COMMERCE_TRACKER,
    }
    HashMap<TrackerName, Tracker> mTrackers = new HashMap<TrackerName, Tracker>();
    synchronized Tracker getTracker(TrackerName trackerId) {
        if (!mTrackers.containsKey(trackerId)) {
            GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
            analytics.getLogger().setLogLevel(Logger.LogLevel.VERBOSE);
            Tracker t = null;
            if(trackerId==TrackerName.APP_TRACKER){
                t= analytics.newTracker("UA-66280994-1");
            }
            mTrackers.put(trackerId, t);
        }
        return mTrackers.get(trackerId);
    }
}

You can see in the newTrackerName(), we have added your analytics unique id we obtain when we registered our app.

In other to make sure that one application class is tracking all our Activity pages, we will first of all change the name of our Application class in the Manifest class to our new Application subclass.

android:name=".AnalyticsApplication"

An instance of the Tracker is create and we will the setScreen() which will take the name of the class as parameter and the send() with the following parameter new HitBuilders.ScreenViewBuilder().build(). The code example is as shown.

Tracker t = ((AnalyticsApplication) getApplication()).getTracker(AnalyticsApplication.TrackerName.APP_TRACKER);
t.setScreenName(this.getClass().getSimpleName());
t.send(new HitBuilders.AppViewBuilder().build());

When you go back the your Google Analytics dashboard, you will see the statistics of visitors on your application as shown below.

google analytics

Now, when you run your application you will see the application interface and how it looks like.

You can download the code for this tutorial below. If you are having hard time downloading the tutorial, kindly contact me.

Remember to subscribe with your email so that you will be among the first to receive our new post once it is published.

If you like this tutorial, please support me by kindly download my new android app in Google play store by clicking the image below

bannerad

OTHER INTERESTING POSTS:

Add a Comment