2015/04/20

Android : GoogleAnalyticsの導入

GoogleAnalyticsの簡単なサンプルです.

Google Analytics Setup

分析対象のアプリケーションからデータを受け取るアナリティクスプロパティとアプリビューを作成します.
詳細はGoogle Analytics V4の”詳細”セクションを参照.

Add Google Play Services to Your Project

Google Play ServiceとGoogle Analyticsのビルドルールをgradleのdependenciesに追加.
下記は執筆時点の最新版を指定している. 実際には下記URLを参考にする.

[Setting Up Google Play Services(https://developer.android.com/google/play-services/setup.html?hl=ja#Setup)

dependencies {
    compile 'com.google.android.gms:play-services:7.0.0'  // Google Play Service
    compile 'com.google.android.gms:play-services-analytics:7.0.0' // Google Analytics
}

Add Permission to You Application

Google Analyticsを利用するにはネットワークアクセスが必要となるため, 次のpermissionを追加する.

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

Use Tracker

Trackerは自身で管理する. Analyticsのオーバーカウントを防ぐためにApplicationクラスで作成・管理する.

public class MyApplication extends Application {
    private final String PROPERTY_ID = "UA-XXXXXXXX-X";

    private Tracker tracker;

    synchronized Tracker getTracker() {
        if (tracker == null) {
            GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
            // Trackerの初期化はR.xmlからも可能.
            // https://developers.google.com/analytics/devguides/collection/android/v4/?hl=ja#analytics-xml
            tracker = analytics.newTracker(PROPERTY_ID);
        }
        return tracker;
    }
}

トラッキング対象のイベントでTrackerを取得しイベント送信すればOK.

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

        MyApplication app = (MyApplication) getApplication();
        Tracker t = app.getTracker();
        // Classインスタンスから名前取得する場合は難読化に注意.
        t.setScreenName("android.m.yuki.googleanalyticssample.MainActivity");
        t.send(new HitBuilders.AppViewBuilder().build());
    }

サンプルの実装は下記.

Reference

Copyright 2015 yuki312 All Right Reserved.

Licensed under the Apache License, Version 2.0 (the “License”);
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.