2016年3月15日 星期二

Android Google Analytics V4 快速使用

使用Google Analytics來觀看app使用情形

1.先前往https://www.google.com/analytics/web/#home/
登入Google帳號,申請一個專案,就會得到一組序號
長這樣: UA-75136xxx-1

2.這裡IDE用Android studio,在build.gradle(Module:app)加入
compile 'com.google.android.gms:play-services-analytics:8.4.0'

3.建立一個app,在res資料夾下建立一個xml資料夾
建立app_tracker.xml檔案,位置/res/xml/app_tracker.xml


    
    300

    
    true

    
    UA-75136xxx-1

    100.0

    true

    

3.建立AnalyticsTrackers.java
package com.terryyamg.analyticstest;

import android.content.Context;

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

import java.util.HashMap;
import java.util.Map;

/**
 * A collection of Google Analytics trackers. Fetch the tracker you need using
 * {@code AnalyticsTrackers.getInstance().get(...)}
 * <p/>
 * This code was generated by Android Studio but can be safely modified by
 * hand at this point.
 * <p/>
 * TODO: Call {@link #initialize(Context)} from an entry point in your app
 * before using this!
 */
public final class AnalyticsTrackers {

    public enum Target {
        APP,
        // Add more trackers here if you need, and update the code in #get(Target) below
    }

    private static AnalyticsTrackers sInstance;

    public static synchronized void initialize(Context context) {
        if (sInstance != null) {
            throw new IllegalStateException("Extra call to initialize analytics trackers");
        }

        sInstance = new AnalyticsTrackers(context);
    }

    public static synchronized AnalyticsTrackers getInstance() {
        if (sInstance == null) {
            throw new IllegalStateException("Call initialize() before getInstance()");
        }

        return sInstance;
    }

    private final Map<Target, Tracker> mTrackers = new HashMap<Target, Tracker>();
    private final Context mContext;

    /**
     * Don't instantiate directly - use {@link #getInstance()} instead.
     */
    private AnalyticsTrackers(Context context) {
        mContext = context.getApplicationContext();
    }

    public synchronized Tracker get(Target target) {
        if (!mTrackers.containsKey(target)) {
            Tracker tracker;
            switch (target) {
                case APP:
                    tracker = GoogleAnalytics.getInstance(mContext).newTracker(R.xml.app_tracker);
                    break;
                default:
                    throw new IllegalArgumentException("Unhandled analytics target " + target);
            }
            mTrackers.put(target, tracker);
        }

        return mTrackers.get(target);
    }
}
4.建立MyApplication.java
package com.terryyamg.analyticstest;

import android.app.Application;

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

public class MyApplication extends Application {
    public static final String TAG = MyApplication.class
            .getSimpleName();

    private static MyApplication mInstance;

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;

        AnalyticsTrackers.initialize(this);
        AnalyticsTrackers.getInstance().get(AnalyticsTrackers.Target.APP);
    }

    public static synchronized MyApplication getInstance() {
        return mInstance;
    }

    public synchronized Tracker getGoogleAnalyticsTracker() {
        AnalyticsTrackers analyticsTrackers = AnalyticsTrackers.getInstance();
        return analyticsTrackers.get(AnalyticsTrackers.Target.APP);
    }

    /***
     * Tracking screen view
     *
     * @param screenName screen name to be displayed on GA dashboard
     */
    public void trackScreenView(String screenName) {
        Tracker t = getGoogleAnalyticsTracker();

        // Set screen name.
        t.setScreenName(screenName);

        // Send a screen view.
        t.send(new HitBuilders.ScreenViewBuilder().build());

        GoogleAnalytics.getInstance(this).dispatchLocalHits();
    }

    /***
     * Tracking exception
     *
     * @param e exception to be tracked
     */
    public void trackException(Exception e) {
        if (e != null) {
            Tracker t = getGoogleAnalyticsTracker();

            t.send(new HitBuilders.ExceptionBuilder()
                            .setDescription(
                                    new StandardExceptionParser(this, null)
                                            .getDescription(Thread.currentThread().getName(), e))
                            .setFatal(false)
                            .build()
            );
        }
    }

    /***
     * Tracking event
     *
     * @param category event category
     * @param action   action of the event
     * @param label    label
     */
    public void trackEvent(String category, String action, String label) {
        Tracker t = getGoogleAnalyticsTracker();

        // Build and send an Event.
        t.send(new HitBuilders.EventBuilder().setCategory(category).setAction(action).setLabel(label).build());
    }

}
5.修改AndroidManifest.xml 加入網路權限
android.permission.INTERNET
android.permission.ACCESS_NETWORK_STATE
在application加入android:name=".MyApplication"

    
    

    
        
            
                

                
            
        
        
        
        
            
                
            
        

        

        
        
            
                
            
        

        
        
    



6.基本上到這邊就完成了,可以在https://analytics.google.com/analytics/web/看到
 7.加入異常或當機狀態,在/res/layout/activity_main.xml加個Button


    

8.MainActivity.java
package com.terryyamg.analyticstest;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

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

        Button btCrash = (Button) findViewById(R.id.btCrash);
        assert btCrash != null;
        btCrash.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try{
                    String name = null;
                    if (name.equals("test")){

                    }
                }catch (Exception e){
                    MyApplication.getInstance().trackException(e); //紀錄在Google Analytics裡
                    Log.i("NullPointerException",e+"");
                }
                //註解掉try catch會直接crash,也會紀錄在Google Analytics裡面
            }
        });
    }
}

當機與例外狀況要等約一天才會出現

其餘還有其他功用,可以參考http://www.androidhive.info/2015/08/android-integrating-google-analytics-v4/

檔案下載:
 https://github.com/terryyamg/AnalyticsTest
參考連結:
http://www.androidhive.info/2015/08/android-integrating-google-analytics-v4/

沒有留言 :

張貼留言