‹ Google Analytics Doc Home

Google Analytics Integration Guide

For the C++ version of cocos2d-x v3.x - (all other versions)

Integration

Open a terminal and use the following command to install the SDKBOX Google Analytics plugin. Make sure you setup the SDKBOX installer correctly.

$ sdkbox import googleanalytics

Important Notice

Please make sure the following settings in your project for plugin to function correctly.

Disable App Transport Security

Adding the following entry to the info.plist file:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

It should look something like this:

Disable Bitcode support

You have to turn off Bitcode support. If you don't cocos2d-x will fail to build.

Set your game requires full screen

If your game doesn't support all screen orientations you will need to check Requires full screen in Xcode. If you do not, your app will fail Apple's submission process.

Whitelist canOpenURL function

This depends on what plugins are in your project. You may need to add the required entry to the info.plist, under LSApplicationQueriesSchemes.

JSON Configuration

SDKBOX Installer will automatically inject a sample configuration to your res/sdkbox_config.json, that you have to modify it before you can use it for your own app

Here is an example of the Google Analytics configuration, you need to replace <TRACKING_CODE> with your specific Google Analytics Tracking Code account information.

"GoogleAnalytics" : {
    "trackingCode" : "<TRACKING_CODE>",
    "anonymizeIp": true
}

Notice

Usage

Initialize Google Analytics

Initialize the plugin where appropriate in your code. We recommend to do this in the AppDelegate::applicationDidFinishLaunching() or AppController:didFinishLaunchingWithOptions(). Make sure to include the appropriate headers:

#include "PluginGoogleAnalytics/PluginGoogleAnalytics.h"
AppDelegate::applicationDidFinishLaunching()
{
     sdkbox::PluginGoogleAnalytics::init();
}

You can always manually stop recording events at any time by calling:

sdkbox::PluginGoogleAnalytics::stopSession();

However, in-order to record events again you must then manually call:

sdkbox::PluginGoogleAnalytics::startSession();

Logged data usually shows up within one day.

Use ECommerce API Sample

    std::map<std::string, std::string> info;

    // transaction info
    info["action"] = "purchase";
    info["transaction"] = "T12345";
    info["affiliation"] = "Google Store - Online";
    info["transactionCouponCode"] = "SUMMER2017";
    info["revenue"] = "37.39";
    info["tax"] = "2.85";
    info["shipping"] = "5.34";

    // product info
    info["productID"] = "P12345";
    info["productName"] = "Android Warhol T-Shirt";
    info["category"] = "Apparel/T-Shirts";
    info["brand"] = "SDKBox";
    info["productVariant"] = "black";
    info["productCouponCode"] = "APPARELSALE";
    info["price"] = "29.20";
    info["quantity"] = "1";

    // currency code
    // https://support.google.com/analytics/answer/6205902?#supported-currencies
    info["currencyCode"] = "EUR";

    PluginGoogleAnalytics::logECommerce(info);
    std::map<std::string, std::string> info;

    // transaction info
    info["action"] = "refund";
    info["transaction"] = "T12345";

    PluginGoogleAnalytics::logECommerce(info);
    std::map<std::string, std::string> info;

    // transaction info
    info["action"] = "refund";
    info["transaction"] = "T12345";

    // product info
    info["productID"] = "P12345";
    info["quantity"] = "1";

    PluginGoogleAnalytics::logECommerce(info);

"action" key value:

"quantity" key value is int fromat, DO NOT use float format

more info, take a look at here ios and android

API Reference

Methods

static void init ( ) ;

initialize the plugin instance.

static void startSession ( ) ;

The analytics session is being explicitly started at plugin initialization time.

static void stopSession ( ) ;

You normally will never stop a session manually.

static void dispatchHits ( ) ;

Manually request dispatch of hits. By default, data is dispatched from the Google Analytics SDK for Android every 5 minutes.

static void dispatchPeriodically ( int seconds ) ;

Change the dispatch info time period to the desired amount of seconds.

static void stopPeriodicalDispatch ( ) ;

Stop periodically sending info. Then manually the dispatchPeridically or dispatchHits should be called.

static void setUser ( const std::string & userID ) ;

Set user ID for this tracking session

static void setDimension ( int index , const std::string & value ) ;

Set value to custom dimension

static void setMetric ( int index , const std::string & value ) ;

Set value to custom metric

static void logScreen ( const std::string & title ) ;

Log screen info. title is the title of a screen. Screens are logical units inside your app you'd like to identify at analytics panel.

static void logEvent ( const std::string & eventCategory ,
                       const std::string & eventAction ,
                       const std::string & eventLabel ,
                       int value ) ;

GoogleAnalytics::logEvent("Achievement", "Unlocked", "Slay 10 dragons", 5);

static void logException ( const std::string & exceptionDescription ,
                           bool isFatal ) ;

Log an exception. It is a basic support for in-app events.

static void logTiming ( const std::string & timingCategory ,
                        int timingInterval ,
                        const std::string & timingName ,
                        const std::string & timingLabel ) ;

Measure a time inside the application.

static void logSocial ( const std::string & socialNetwork ,
                        const std::string & socialAction ,
                        const std::string & socialTarget ) ;

Log a social event.

static void setDryRun ( bool enable ) ;

While running on dry run, the tracked events won't be sent to the actual analytics account.

static void enableAdvertisingTracking ( bool enable ) ;

Enable advertising tracking when in google's ad vendors.

static void createTracker ( const std::string & trackerId ) ;

Create a tracker identified by the google analytics tracker id XX-YYYYYYYY-Z. If the tracker already existed, no new tracker will be created. In any case, the tracker associated with tracker id will be set as default tracker for analytics operations.

static void enableTracker ( const std::string & trackerId ) ;

Enable a tracker identified by a trackerId. If the tracker does not exist, nothing will happen.

Listeners

Manual Integration

If the SDKBOX Installer fails to complete successfully, it is possible to integrate SDKBOX manually. If the installer complete successfully, please do not complete anymore of this document. It is not necessary.

These steps are listed last in this document on purpose as they are seldom needed. If you find yourself using these steps, please, after completing, double back and re-read the steps above for other integration items.

Manual Integration For iOS

Drag and drop the following frameworks from the plugins/ios folder of theGoogleAnalytics bundle into your Xcode project, check Copy items if needed when adding frameworks:

sdkbox.framework

PluginGoogleAnalytics.framework

The above frameworks depend upon other frameworks. You also need to add the following system frameworks, if you don't already have them:

CoreData.framework

Security.framework

SystemConfiguration.framework

libz.dylib

libsqlite3.dylib

libAdIdAccess.a

AdSupport.framework

Add a linker flag, if your setup requires it, to: Target -> Build Settings -> Linking -> Other Linker Flags:

-force_load /path/to/libAdIdAccess.a

Manual Integration For Android

SDKBOX supports three different kinds of Android projects command-line, eclipse and Android Studio.

Copy Files

Copy the following jar files from plugin/android/libs folder of this bundle into your project’s /libs folder.

PluginGoogleAnalytics.jar

sdkbox.jar

Copy jni libs

Copy and overwrite all the folders from plugin/android/jni to your <project_root>/jni/ directory.

Note: sdkbox link with gnustl by default, if your project link with c++static please replace the files in <project_root>/jni/<plugin_name>/libs with files in <project_root>/jni/<plugin_name>/libs_c++_static folder

Edit AndroidManifest.xml

Include the following permissions above the application tag:

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

There are also a few necessary meta-data tags that also need to be added:

<meta-data android:name="com.google.android.gms.version"
    android:value="@integer/google_play_services_version" />
<meta-data
    android:name="com.google.android.gms.analytics.globalConfigResource"
    android:resource="@xml/global_tracker" />

Next, register the AnalyticsReceiver:

<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"/>

If you want to use optional Receivers, specify them next:

<!-- 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" />

Edit the meta-data files

In the step above a file named global_tracker.xml was specified. This file needs to be created and populated with a few required settings. So where does it go? Take a look again at the code tag from above:

<meta-data
    android:name="com.google.android.gms.analytics.globalConfigResource"
    android:resource="@xml/global_tracker" />

Notice the android:resource= attribute. This gives you the path of where to create this file, in this case it would be <project_root>/res/xml.

This file needs to contain required settings. The contents of this file could be something like this:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <integer name="ga_dispatchPeriod">300</integer>
    <string name="ga_logLevel">verbose</string>
</resources>

Edit Android.mk

Edit <project_root>/jni/Android.mk to:

Add additional requirements to LOCAL_WHOLE_STATIC_LIBRARIES:

LOCAL_WHOLE_STATIC_LIBRARIES += PluginGoogleAnalytics
LOCAL_WHOLE_STATIC_LIBRARIES += sdkbox

Add a call to:

$(call import-add-path,$(LOCAL_PATH))

before any import-module statements.

Add additional import-module statements at the end:

$(call import-module, ./sdkbox)
$(call import-module, ./plugingoogleanalytics)

This means that your ordering should look similar to this:

$(call import-add-path,$(LOCAL_PATH))
$(call import-module, ./sdkbox)
$(call import-module, ./plugingoogleanalytics)

Note: It is important to make sure these statements are above the existing $(call import-module,./prebuilt-mk) statement, if you are using the pre-built libraries.

Modify Application.mk (Cocos2d-x v3.0 to v3.2 only)

Edit <project_root>/jni/Application.mk to make sure APP_STL is defined correctly. If Application.mk contains APP_STL := c++_static, it should be changed to:

APP_STL := gnustl_static

Modify Cocos2dxActivity.java

Note: When using Cocos2d-x from source, different versions have Cocos2dxActivity.java in a different location. One way to find the location is to look in proj.android/project.properties. Example: android.library.reference.1=../../cocos2d-x/cocos/platform/android/java

In this case, Cocos2dxActivity.java should be located at:

../../cocos2d-x/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java
import android.content.Intent;
import com.sdkbox.plugin.SDKBox;
onLoadNativeLibraries();
SDKBox.init(this);
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
          if(!SDKBox.onActivityResult(requestCode, resultCode, data)) {
            super.onActivityResult(requestCode, resultCode, data);
          }
    }
    @Override
    protected void onStart() {
          super.onStart();
          SDKBox.onStart();
    }
    @Override
    protected void onStop() {
          super.onStop();
          SDKBox.onStop();
    }
    @Override
    protected void onResume() {
          super.onResume();
          SDKBox.onResume();
    }
    @Override
    protected void onPause() {
          super.onPause();
          SDKBox.onPause();
    }
    @Override
    public void onBackPressed() {
          if(!SDKBox.onBackPressed()) {
            super.onBackPressed();
          }
    }

Manual Integration for Google Play Services SDK (dependent library only)

Suggestion

Please try the sdkbox installer first. It will do all the following step for you automatically.

$ sdkbox import googleplayservices

Modify project.properties

An Android Library Reference for Google Play Services is required. The path will be different depending upon your setup. Also, this is an additional download that does not come as part of a standard install. To install use the sdk installer and choose extras->google play services. Here is an example of what this line could look like:

android.library.reference.1=
../android/sdk.latest/extras/google/google_play_services/libproject/
google-play-services_lib

Note: if you already have an android.library.reference.1 you can add another by incrementing the number as android.library.reference.2, etc.

Integration manually

We make a lite version of Google Play Services, the project repo is https://github.com/darkdukey/Google-Play-Service-Lite

Copy Files

Copy the gps folder from plugin folder of this bundle into your project’s /libs folder.

Modify files for Eclipse

  1. Modify project.properties
# For source project
android.library.reference.2=../cocos2d/cocos/platform/android/java/libs/gps/

# Or
# For framework project
android.library.reference.1=libs/gps/

Modify files for Android Studio

1. Modify cocos2d/cocos/platform/android/libcocos2dx/build.gradle
 dependencies {
+    compile project(':gps')
     compile fileTree(dir: '../java/libs', include: ['*.jar'])
 }
2. Modify proj.android-studio/app/project.properties
 # Project target.
 target=android-10
+android.library.reference.1=../cocos2d/cocos/platform/android/java/libs/gps/
3. Modify proj.android-studio/settings.gradle
 project(':libcocos2dx').projectDir = new File(settingsDir, '../cocos2d/cocos/platform/android/libcocos2dx')
 include ':your_project_name'
 project(':your_project_name').projectDir = new File(settingsDir, 'app')
+
+include ':gps'
+project(':gps').projectDir = new File(settingsDir, '../cocos2d/cocos/platform/android/java/libs/gps')

Proguard (optional)

proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
# cocos2d-x
-keep public class org.cocos2dx.** { *; }
-dontwarn org.cocos2dx.**
-keep public class com.chukong.** { *; }
-dontwarn com.chukong.**

# google play service
-keep class com.google.android.gms.** { *; }
-dontwarn com.google.android.gms.**

-keep class * extends java.util.ListResourceBundle {
    protected Object[][] getContents();
}

-keep public class com.google.android.gms.common.internal.safeparcel.SafeParcelable {
    public static final *** NULL;
}

-keepnames @com.google.android.gms.common.annotation.KeepName class *
-keepclassmembernames class * {
    @com.google.android.gms.common.annotation.KeepName *;
}

-keepnames class * implements android.os.Parcelable {
    public static final ** CREATOR;
}

#sdkbox
-keep class com.sdkbox.** { *; }
-dontwarn com.sdkbox.**

Note: Proguard only works with Release builds (i.e cocos run -m release) debug builds do not invoke Proguard rules.