Saturday, April 23, 2016

android - How to add Google Analytics to an app

AndroidMnifest.xml

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

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

    <application
        android:name=".AndroidCodeSnippetsApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        >
        <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>
        <activity
            android:name=".DetailsActivity"></activity>
    </application>

</manifest>
AndroidCodeSnippetsApplication.java

package com.cfsuman.me.androidcodesnippets;


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


public class AndroidCodeSnippetsApplication extends Application {
    private Tracker mTracker;

    synchronized public Tracker getDefaultTracker() {
        if (mTracker == null) {
            GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
            mTracker = analytics.newTracker(R.xml.analytics_tracker);
        }
        return mTracker;
    }
}
res/xml/analytics_tracker.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="ga_trackingId">XX-XXXXXXXX-XX</string>
    <string name="ga_sampleFrequency">100.0</string>
    <integer name="ga_sessionTimeout">30</integer>
    <bool name="ga_autoActivityTracking">true</bool>
    <bool name="ga_anonymizeIp">false</bool>
    <bool name="ga_reportUncaughtExceptions">true</bool>

    <screenName name="com.cfsuman.me.androidcodesnippets.MainActivity">Home Screen</screenName>
    <screenName name="com.cfsuman.me.androidcodesnippets.DetailsActivity">Details Screen</screenName>
</resources>
project build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.3.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files

        // For Google Analytics
        classpath 'com.google.gms:google-services:2.0.0-alpha6'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
app build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"

    defaultConfig {
        applicationId "com.cfsuman.me.androidcodesnippets"
        minSdkVersion 16
        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.2.1'
    //compile 'com.android.support:cardview-v7:23.2.1'
    //compile 'com.android.support:recyclerview-v7:23.2.1'
    //compile 'com.android.support:design:23.2.1'

    // For Google Analytics
    compile 'com.google.android.gms:play-services-analytics:8.4.0'
}

// For Google Analytics
apply plugin: 'com.google.gms.google-services'
activity_main.xml

<?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:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity"
    android:background="#b3bca5"
    >
    <Button
        android:id="@+id/btn_buy"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="BUY NOW"
        android:layout_centerInParent="true"
        />
    <Button
        android:id="@+id/btn_next"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:text="Go Next Screen"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;

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


public class MainActivity extends AppCompatActivity {

    private Context mContext;
    private Activity mActivity;

    private RelativeLayout mRelativeLayout;
    private Button mButtonBuy;
    private Button mButtonNext;

    // For Google Analytics
    private Tracker mTracker;
    private String mActivityName = "Home Screen";

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

        // Obtain the shared Tracker instance.
        AndroidCodeSnippetsApplication application = (AndroidCodeSnippetsApplication) getApplication();
        mTracker = application.getDefaultTracker();

        // Get the application context
        mContext = getApplicationContext();

        // Get the activity
        mActivity = MainActivity.this;

        // Get the widgets reference from XML layout
        mRelativeLayout = (RelativeLayout) findViewById(R.id.rl);
        mButtonBuy = (Button) findViewById(R.id.btn_buy);
        mButtonNext = (Button) findViewById(R.id.btn_next);

        // Set a click listener for the buy button widget
        mButtonBuy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Show a Toast message
                Toast.makeText(mContext,"Buy Button Click",Toast.LENGTH_SHORT).show();

                // Send this event to Google Analytics
                mTracker.send(new HitBuilders.EventBuilder()
                        .setCategory("Action")
                        .setAction("Buy Button Click")
                        .build());
           }
        });

        // Set a click listener for the next button widget
        mButtonNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mActivity,DetailsActivity.class);
                startActivity(intent);
            }
        });
    }

    @Override
    public void onResume(){
        super.onResume();
        // For Google Analytics
        mTracker.setScreenName(mActivityName);
        mTracker.send(new HitBuilders.ScreenViewBuilder().build());
    }
}
activity_details.xml

<?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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.cfsuman.me.androidcodesnippets.DetailsActivity"
    >
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="DETAILS ACTIVITY"
        android:fontFamily="sans-serif-condensed"
        android:textSize="50sp"
        android:layout_centerInParent="true"
        />
</RelativeLayout>
DetailsActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

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

public class DetailsActivity extends AppCompatActivity {
    // For Google Analytics
    private Tracker mTracker;
    private String mActivityName = "Home Screen";

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

        // Obtain the shared Tracker instance.
        AndroidCodeSnippetsApplication application = (AndroidCodeSnippetsApplication) getApplication();
        mTracker = application.getDefaultTracker();
    }

    @Override
    public void onResume(){
        super.onResume();
        // For Google Analytics
        mTracker.setScreenName(mActivityName);
        mTracker.send(new HitBuilders.ScreenViewBuilder().build());
    }
}