Home  >  Android

Integrate Google Analytics with Android App Example

By Arvind Rai, September 17, 2015
This page will show you how to integrate Google Analytics with Android App with Example. We will describe it step by step and with complete example. For the development I am using eclipse and Android 4.4w. Google analytics is a strong tool to analyze user hit to our app. It will help to improve our app functionality and performance. User's live action on app gives the idea where to improve our app. Now let's start to integrate Google analytics step by step.

Step 1: Create Google analytics Account

Create an account in mobile Google analytics and configure your android app. Find the link.
http://www.google.com/analytics/mobile/
You will get a tracking id for your app. It will look like UA-xxxxxxxx-x.

Step 2: Configure google-play-services.jar

We need a JAR google-play-services.jar which will be kept in lib directory of our project. We can get latest one from updating Android SDK for library project google-play-services_lib.

Step 3: Tracking Id Configuration in XML

Find the project structure in eclipse.
Integrate Google Analytics with Android App Example
First of all we need to create a folder named as xml in which we will keep our analytics configuration file.
xml/analytics.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="ga_trackingId">UA-xxxxxxxx-x</string>
    <bool name="ga_autoActivityTracking">true</bool>
    <bool name="ga_reportUncaughtExceptions">true</bool>    
</resources> 
Here we will configure tracking id and other attributes. Replace UA-xxxxxxxx-x with your actual tracking id.

Step 4: Create Application Class

Create a class which will extend android.app.Application. Here we will create a method that will return Tracker. To get tracker we will use analytics xml file.
AnalyticsApplication.java
package com.concretepage;
import android.app.Application;
import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.Tracker;
public class AnalyticsApplication extends Application {
  private Tracker tracker;
  synchronized public Tracker getDefaultTracker() {
    if (tracker == null) {
      GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
      tracker = analytics.newTracker(R.xml.analytics);
    }
    return tracker;
  }
} 

Step 5: Configure AndroidManifest.xml for Application Class and Required Permission

Configure Application in AndroidManifest.xml with attribute android:name.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.concretepage"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="14"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <application 
        android:name="com.concretepage.AnalyticsApplication"
        android:allowBackup ="false"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity android:name="com.concretepage.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest> 
We need to introduce two permissions.
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> 

Step 6: Use Tracker in Activity Class for Activity and Event Tracking

Now we will use Tracker in our Activity classes returned by Application class. Add tracker in only those Activity which are needed to be analyzed. Google analytics provide Activity tracking and Event tracking. Activity class Access Tracking:
Find the code snippet for activity class access tracking, which can be written within onCreate(), onResume() etc methods.
AnalyticsApplication application = (AnalyticsApplication) getApplication();
Tracker mTracker = application.getDefaultTracker();
mTracker.setScreenName("MainActivity");
mTracker.send(new HitBuilders.ScreenViewBuilder().build()); 
Event Tracking:
Find the code snippet for event tracking. Here we will introduce Category and Action for an event like button click.
AnalyticsApplication application = (AnalyticsApplication) getApplication();
Tracker mTracker = application.getDefaultTracker();
mTracker.setScreenName("MainActivity");
mTracker.send(new HitBuilders.EventBuilder()
.setCategory(category)
.setAction(action)
.build()); 
Now find our Activity class used in our example.
MainActivity.java
package com.concretepage;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_main);
	handleScreenTrackingAnalytics();
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
         getMenuInflater().inflate(R.menu.menu_main, menu);
         return true;
    }
    public void showMessage(View view) {
    	handleEventTrackingAnalytics("Button Click", "Show Message");
    	Toast toast = Toast.makeText(getApplicationContext(), "Button is clicked.", Toast.LENGTH_SHORT);
    	toast.show();
    }
    private void handleScreenTrackingAnalytics() {
        AnalyticsApplication application = (AnalyticsApplication) getApplication();
        Tracker mTracker = application.getDefaultTracker();
        mTracker.setScreenName("MainActivity");
        mTracker.send(new HitBuilders.ScreenViewBuilder().build());
    }
    private void handleEventTrackingAnalytics(final String category, final String action) {
        AnalyticsApplication application = (AnalyticsApplication) getApplication();
        Tracker mTracker = application.getDefaultTracker();
        mTracker.setScreenName("MainActivity");
        mTracker.send(new HitBuilders.EventBuilder()
        .setCategory(category)
        .setAction(action)
        .build());
    }
} 
Find the layout used in the example.
layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"    
    tools:context=".MainActivity"
    android:id="@+id/myLayout">
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/btnmsg"
        android:onClick="showMessage"/>
</LinearLayout> 	 

Step 7: Test the Integration

Now we are done with Google analytics integration with our app. Run the app and we will be able to see hit in Google analytics. Find the screen shot.
Integrate Google Analytics with Android App Example

References

Add Analytics to Your Android App

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS
comments powered by Disqus


Copyright ©2017 concretepage.com, all rights reserved |Privacy Policy | Contact Us