Integrating Google Analytics In Your Android Game

Discussion in 'Technical Discussion' started by yogeshojha, Apr 1, 2017.

  1. yogeshojha

    yogeshojha Boxer

    Joined:
    Feb 16, 2017
    Messages:
    9
    Likes Received:
    6
    Hello Everyone.

    I have successfully integrated Google analytics in my Game and would like to share with you.

    Difficulty level: EASY
    Although Google Analytics provides huge number of analytical features, I am going to cover only the essential modules necessary for every game.

    Creating Google Analytics Property
    1. Sign in to your Google Analytics account.
    2. Select the Admin tab.
    3. In the ACCOUNT dropdown, click on Create new account. (Or select the property if you created one already)
    4. Select Mobile App in the new property form.
    5. Enter the App Name.
    6. Select Industry Category & Report Time Zone and click on Get Tracking ID.
    7. In the next screen you will be shown your property Tracking ID.
    The tracking ID should look like UA-XXXXXXXX-X. (Note down this tracking id we need this later)
    [​IMG]


    After this open the project inside android studio, and open build.gradle (Module: app)
    Add this inside your build.gradle

    compile 'com.google.android.gms:play-services-analytics:8.+'

    Create a folder named xml under res. Inside xml folder, create an xml file named app_tracker.xml and add below analytics configuration.

    just copy pase everything and replace your tracking id you got from above steps

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
    <integer name="ga_sessionTimeout">300</integer>
    <bool name="ga_autoActivityTracking">true</bool>
    <string name="ga_trackingId">UA-XXXXXX-1</string>
    <string name="ga_sampleFrequency">100.0</string>
    <bool name="ga_reportUncaughtExceptions">true</bool>
    </resources>


    Make sure that you replaced the ga_trackingId with your tracking ID which we retrieved in above section.
    Under app package, create a class named AnalyticsTrackers.java with the below code.


    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;
    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);
    }
    }


    Create a class named MyApplication.java under app package and paste everything.

    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());
    }

    }

    Open AndroidManifest.xml and do the below changes
    Add MyApplication to <application> tag.
    I assume INTERNET and ACCESS_NETWORK_STATE are already given.
    Initially your manifest application will look like this
    <application android:label="@string/app_name"
    android:icon="@drawable/icon"
    android:allowBackup="true">

    Now add android:name=".MyApplication" which looks simillar to this

    <application android:label="@string/app_name"
    android:icon="@drawable/icon"
    android:name=".MyApplication"
    android:allowBackup="true">

    Add the receivers and services mentioned below. These are optional, but recommended for accurate results.
    This should be pasted before </application>.
    <receiver
    android:name="com.google.android.gms.analytics.AnalyticsReceiver"
    android:enabled="true">
    <intent-filter>
    <action android:name="com.google.android.gms.analytics.ANALYTICS_DISPATCH" />
    </intent-filter>
    </receiver>

    <service
    android:name="com.google.android.gms.analytics.AnalyticsService"
    android:enabled="true"
    android:exported="false" />

    <!--
    Optionally, register CampaignTrackingReceiver and CampaignTrackingService to enable
    installation campaign reporting
    -->
    <receiver
    android:name="com.google.android.gms.analytics.CampaignTrackingReceiver"
    android:exported="true">
    <intent-filter>
    <action android:name="com.android.vending.INSTALL_REFERRER" />
    </intent-filter>
    </receiver>
    <service android:name="com.google.android.gms.analytics.CampaignTrackingService" />

    VOILA ! your Google Analytics setup is done. Now if you run the app, you should see one user on Google Analytics dashboard. You won’t be able to see the user on the dashboard instantly due to slight delay in google analytics. You will have to wait for 2-3 mins to see the users on the dashboard. If no users are displayed, make sure that you followed the above steps correctly.

    Inside your acount you will be able to see Realtime tab. Click there.
    Initiallly this look like
    [​IMG]

    When you open the game this should look like this
    [​IMG]

    Let me know if this worked for you.

    Since I work as a android developer, I cant tell you about ios, but if you have followed this corretly then this should work for you.
     

    Attached Files:

  2. jcalle

    jcalle Miniboss Boxer

    Joined:
    Sep 25, 2015
    Messages:
    1,193
    Likes Received:
    541
    Thank you.
    I'll try it.
     
  3. cdspy2000

    cdspy2000 Boxer

    Joined:
    Jun 22, 2016
    Messages:
    15
    Likes Received:
    2
    please make video tutorial !!!!!
     
  4. yogeshojha

    yogeshojha Boxer

    Joined:
    Feb 16, 2017
    Messages:
    9
    Likes Received:
    6
    @cdspy2000 I would love to make the video, let me get some free time. I will surely make it
     
  5. cdspy2000

    cdspy2000 Boxer

    Joined:
    Jun 22, 2016
    Messages:
    15
    Likes Received:
    2
    Thank You Very Much for exellent info.
     
  6. Christoph

    Christoph Miniboss Boxer

    Joined:
    Oct 4, 2015
    Messages:
    2,807
    Likes Received:
    2,309
    Thanks a lot. Any chance having a small tutorial on how to do it in Eclipse?

    Also, just a heads up. Use [ CODE ][ /CODE ] tags (without spaces) for the code to make sure it doesn't get messed up by any automatic formatting.
     
  7. bmsingha

    bmsingha Serious Boxer

    Joined:
    Feb 17, 2016
    Messages:
    517
    Likes Received:
    198
    Good shared stuff mate,
     
  8. Rainyday

    Rainyday Avid Boxer

    Joined:
    Nov 21, 2016
    Messages:
    116
    Likes Received:
    41
    If you can explain how to do it in eclipse .. oooh that would be amazing


    Thanks
     
  9. whitedogapp

    whitedogapp Avid Boxer

    Joined:
    Oct 8, 2015
    Messages:
    295
    Likes Received:
    72
    Buildbox export eclipse file do u have tutorial?
     
  10. sharma.shivam

    sharma.shivam Avid Boxer

    Joined:
    Oct 23, 2016
    Messages:
    180
    Likes Received:
    10
    hi,i tried the above steps but it shows me 3 errors.has anyone successfully integrated it before?
     

Share This Page