Pages

Label

Sabtu, 01 Februari 2014

Integrating Google Analytics in Android

Happy new Year Guys !!! 
Today I am going to put an example of Google Analytic integration in Android App. You have to use Google Analytic SDK for Android app integration.It is easy for native Android developers to collect user engagement data from their applications by using Analytics.
You can use the Google Analytic reports to measure:
  • The number of active users are using their applications.
  • From where in the world the application is being used.
  • Adoption and usage of specific features.
  • Crashes and exceptions.
  • In-app purchases and transactions.
  • And many other useful metrics...
The Google Analytics SDK also gives you the tools to monitor the success of mobile marketing campaigns. Connect user interactions with paid ads, Google Play downloads, and subsequent in-app usage and Ecommerce transactions. Google Analytics provides a powerful platform to measure and optimize all of your application marketing efforts.

Now I am going to give a working  example code of Google Analytic integration in Android.
 Step First
You have to create a Google Analytic account by using your gamil account.You can visit this link for account creation. After account creation you have to setup Application related information . You can do this by going Admin section of your Google Analytic Account.  This will generate a unique key (UA-xxxxxxxxxx) for your application. By using this key You can track your application by putting some simple code in your existing application.
Step Second 
Add analytics.xml configuration file in your application values folder.
In the Google Analytics SDK for Android v2.x and higher, you can configure your EasyTracker implementation using parameters defined in your analytics.xml file. For more detail tou can visit this link
<?xml version="1.0"encoding="utf-8"?>
<resources>
    <!-- Replace placeholder ID with your tracking ID -->
    <string name="ga_trackingId">UA-47704140-1</string>
    <!-- Enable automatic activity tracking -->
    <bool name="ga_autoActivityTracking">true</bool>
    <!-- Enable automatic exception tracking -->
    <bool name="ga_reportUncaughtExceptions">true</bool>
     <!-- Set Your Application Screen as per your choice -->
    <string name="com.example.helloworld.GATrackingActivityOne">screen One</string>
    <string name="com.example.helloworld.GATrackingActivityTwo">screen Two</string>
</resources>
Step Third
Android Activity Layout
In my example code there is two activity . So I am putting two different activities xml code.
ga_tracking_activity.xml
<?xml version="1.0"encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_margin="10dp"
        android:text="@string/info"
        android:textColor="#A52A2A"
        android:textSize="16sp"
        android:textStyle="bold" />
    <Button
        android:id="@+id/trackEvent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_margin="10dp"
        android:text="@string/track_event" />
    <Button
        android:id="@+id/trackCrash"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_margin="10dp"
        android:text="@string/track_crash" />
    <Button
        android:id="@+id/second_screen"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_margin="10dp"
        android:text="@string/second_screen" />
</LinearLayout>
ga_tracking2_activity.xml
<?xml version="1.0"encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_margin="10dp"
        android:text="@string/second_screen"
        android:textColor="#A52A2A"
        android:textSize="16sp"
        android:textStyle="bold" />
</LinearLayout>
Step Fourth 
Android Activity code. here I am using Google analytic SDK to give you an example of  Tracking foillowing things.
  1. Event Tracking (like tracking of button click  in your app)
  2. Crash Tracking  (like Known Exception try-catch block)
  3. whole Screen Tacking ( App info or Activity to activity tracking) 
Please go through the comment  given in application code to understand more accurately to using Google Analytic SDK in your application.
1. GATrackingActivityOne (Activity First/ Screen First)
import com.google.analytics.tracking.android.EasyTracker;
importcom.google.analytics.tracking.android.GAServiceManager;
importcom.google.analytics.tracking.android.GoogleAnalytics;
importcom.google.analytics.tracking.android.Logger.LogLevel;
importcom.google.analytics.tracking.android.MapBuilder;
importcom.google.analytics.tracking.android.StandardExceptionParser;
importandroid.app.Activity;
importandroid.content.Intent;
import android.os.Bundle;
import android.view.View;
importandroid.view.View.OnClickListener; 
public classGATrackingActivityOne extends Activity{
       private EasyTracker easyTracker = null;
       private static GoogleAnalytics mGa = null;      
         // Dispatch period in seconds.
         private static final int GA_DISPATCH_PERIOD = 30; 
         // Prevent hits from being sent to reports, i.e. during testing.
       // When true, dryRun flag prevents data from being processed with reports.
         private static final boolean GA_IS_DRY_RUN = false; 
         // GA Logger verbosity.
         private static final LogLevel GA_LOG_VERBOSITY = LogLevel.VERBOSE; 
       @Override
       protected void onCreate(Bundle savedInstanceState) {
              // TODO Auto-generated method stub
              super.onCreate(savedInstanceState);
              setContentView(R.layout.ga_tracking_activity); 
              // Initialize a Easy tracker
              easyTracker = EasyTracker.getInstance(GATrackingActivityOne.this);                         mGa = GoogleAnalytics.getInstance(this);               
              // Set dispatch period.
           GAServiceManager.getInstance().setLocalDispatchPeriod(GA_DISPATCH_PERIOD); 
           // Set dryRun flag.
           mGa.setDryRun(GA_IS_DRY_RUN); 
           // Set Logger verbosity.
           mGa.getLogger().setLogLevel(GA_LOG_VERBOSITY); 
  findViewById(R.id.trackEvent).setOnClickListener(new OnClickListener() {
                     @Override
                     public void onClick(View v) {
                           // MapBuilder.createEvent().build() returns a Map of event fields and values
                           // that are set and sent with the hit.
                           easyTracker.send(MapBuilder
                                         .createEvent("Click On Event",     // Event category (required)...ui_action
                                                       "S_1 Button Pressed"// Event action (required)...button_press
                                                       "Event_button",   // Event label
                                                       null)            // Event value
                                                       .build()
                                         ); 
                    }
              }); 
  findViewById(R.id.trackCrash).setOnClickListener(newView.OnClickListener() {
                     @Override
                     public void onClick(View v) {

                           try {
                                  int i = 3/0;
                           } catch (ArithmeticException e) {
                                  e.printStackTrace();
                                  // StandardExceptionParser is provided to help get meaningful Exception descriptions.
                                  easyTracker.send(MapBuilder
                                                .createException(newStandardExceptionParser(GATrackingActivityOne.this, null) // Context and optional collection of package names
                                                // to be used in reporting the exception.
                                                .getDescription(Thread.currentThread().getName(),    // The name of the thread on which the exception occurred.
                                                              e),                                  // The exception.
                                                              false).build() );  }                                          // False indicates a fatal exception
                     }
              });            
             
 findViewById(R.id.second_screen).setOnClickListener(new OnClickListener() {                                        @Override
                     public void onClick(View arg0) {
 startActivity(newIntent(GATrackingActivityOne.this, GATrackingActivityTwo.class));      
                                               }
              });
       }
       @Override
       protected void onStart() {
              super.onStart();
               EasyTracker.getInstance(this).activityStart(this);
       }
       @Override
       protected void onStop() {
              super.onStop();
               EasyTracker.getInstance(this).activityStop(this);
       }
}

2. GATrackingActivityTwo (Second activity/ Screen 2)
importcom.google.analytics.tracking.android.EasyTracker;
importandroid.app.Activity;
import android.os.Bundle;
public classGATrackingActivityTwo extends Activity {
       @Override
       protected void onCreate(Bundle savedInstanceState) {
              // TODO Auto-generated method stub
              super.onCreate(savedInstanceState);
              setContentView(R.layout.ga_tracking2_activity);            
       }
       @Override
       protected void onStart() {
              super.onStart();
              EasyTracker.getInstance(this).activityStart(this);
       }
       @Override
       protected void onStop() {
              EasyTracker.getInstance(this).activityStart(this);
              super.onStop();
       }
      
}
This is the all about the Google analytic integration in  android. You can explore some more about Google analytic by using following links. You can download this application from This Link
Reference:-
https://developers.google.com/analytics/devguides/collection/android/v2/exceptions
https://developers.google.com/analytics/devguides/collection/android/v3/advanced
https://developers.google.com/analytics/devguides/collection/android/v3/migration
  Happy Coding !!!! 

0 komentar:

Posting Komentar

 
[tutup]