‹ TUNE Doc Home

TUNE Integration Guide

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

SDK Version

iOS 5.1.0 android: 4.9.0

Integration

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

$ sdkbox import tune

Important Notice

Please make sure the following settings in your project to make the plugin work well.

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 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 setting 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 sdkbox_config.json, that you have to modify it before you can use it for your own app

Here is an example of the Tune configuration, you need to replace <TUNE ID> and <TUNE KEY> with your specific Tune ID account information. Here is an example adding Tune:

"Tune":{
    "id":"<TUNE ID>",
    "key":"<TUNE KEY>",
    "debug":false
}

Extra steps

Setup iOS

#import <Tune/Tune.h>

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary *)options {
    // Pass the deep link URL to Tune
    [Tune handleOpenURL:url options:options];
    // Take care of the redirect yourself here
    ...
    return YES;
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    // Pass the deep link URL to Tune
    [Tune handleOpenURL:url sourceApplication:sourceApplication];
    // Take care of the redirect yourself here
    ...
    return YES;
}
- (BOOL)application:(UIApplication *)application continueUserActivity:(nonnull NSUserActivity *)userActivity restorationHandler:(nonnull void (^)(NSArray * _Nullable))restorationHandler {
    BOOL handledByTune = [Tune handleContinueUserActivity:userActivity restorationHandler:restorationHandler];
    // If handledByTune is false, take care of the redirect yourself
    if (!handledByTune) {
        ...
    }
    return YES;
}

Usage

Initialize Tune

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. init() and measureSession() are required. Example:

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

Using Tune

After initialization you can begin to use the Tune functionality. Tune uses a concept of events (also known as MAT Native Event Types). You log events that you care about and you can later view them using the web-based report viewer. Tune provides a structure for these events in their documentation. Example:

{
    PluginTune::measureEventName("purchase");
    PluginTune::measureEventId(1122334455);
        TuneEvent event;
    event.eventName = "purchase2";
    event.refId     = "RJ1357";
    event.searchString = "sweet crisp red apples";
    event.attribute1 = "crisp";
    event.attribute2 = "red";
    event.quantity = 3;
    PluginTune::measureEvent(event);
}

Notice that at the end of the event PluginTune::measureEvent(event) was called. This takes care of logging our event.

API Reference

Methods

static void setListener ( TuneListener * listener ) ;

set a listener to listen for event changes.

static TuneListener * getListener ( ) ;

Get the listener

static void removeListener ( ) ;

remove the listener, and can't listen to events anymore

static void init ( ) ;

init the instance.

static void setDebugMode ( bool enable ) ;

Specifies that the server responses should include debug information.

@warning This is only for testing. You must turn this off for release builds.
static void setAllowDuplicateRequests ( bool allow ) ;

Set to YES to allow duplicate requests to be registered with the MAT server.

@warning This is only for testing. You must turn this off for release builds.
SDKBOX_DEPRECATED ( "checkForDeferredDeepLink" ) static void checkForDeferredDeeplinkWithTimeout ( double timeout ) ;

Check for a deferred deeplink entry point upon app installation. This is safe to call at every app launch, since the function does nothing unless this is the first launch.

The timeout parameter should be set in keeping with the normal first-launch
time and user experience of your app.
static void checkForDeferredDeepLink ( ) ;

Check for a deferred deeplink entry point upon app installation. This is safe to call at every app launch, since the function does nothing unless this is the first launch.

static void automateIapEventMeasurement ( bool automate ) ;

Enable automatic measurement of app store in-app-purchase events. When enabled, your code should not explicitly measure events for successful purchases related to StoreKit to avoid event duplication.

@platform iOS
static void setFacebookEventLogging ( bool logging , bool limit ) ;

Set whether the MAT events should also be logged to the Facebook SDK. This flag is ignored if the Facebook SDK is not present.

should be restricted from being used for other than analytics and conversions.  Defaults to false.
This value is stored on the device and persists across app launches.
static void setExistingUser ( bool existingUser ) ;

Set whether this is an existing user or a new one. This is generally used to distinguish users who were using previous versions of the app, prior to integration of the MAT SDK. The default is to assume a new user.

See http://support.mobileapptracking.com/entries/22621001-Handling-Installs-prior-to-SDK-implementation
static void setAppleAdvertisingIdentifier ( const std::string & appleAdvertisingIdentifier ,
                                            bool adTrackingEnabled ) ;

Set the Apple Advertising Identifier available in iOS 6.

@platform iOS
static void setAppleVendorIdentifier ( const std::string & appleVendorIdentifier ) ;

Set the Apple Vendor Identifier available in iOS 6.

@platform iOS
static void setCurrencyCode ( const std::string & currencyCode ) ;

Sets the currency code.

Default: USD
static void setJailbroken ( bool jailbroken ) ;

Sets the jailbroken device flag.

@platform iOS
static void setPackageName ( const std::string & packageName ) ;

Sets the package name (bundle identifier). Defaults to the Bundle Identifier of the app that is running the sdk.

static void setShouldAutoDetectJailbroken ( bool autoDetect ) ;

Specifies if the sdk should auto detect if the iOS device is jailbroken.

static void setShouldAutoGenerateAppleVendorIdentifier ( bool autoGenerate ) ;

Specifies if the sdk should pull the Apple Vendor Identifier from the device. Note that setting to false will clear any previously set value for the property.

@platform iOS
SDKBOX_DEPRECATED ( "setPackageName" ) static void setSiteId ( const std::string & siteId ) ;

Sets the site ID.

static void setTRUSTeId ( const std::string & tpid ) ;

Set the TRUSTe Trusted Preference Identifier (TPID).

static void setUserEmail ( const std::string & userEmail ) ;

Sets the user's email address.

static void setUserId ( const std::string & userId ) ;

Sets the user ID.

static void setUserName ( const std::string & userName ) ;

Sets the user's name.

static void setPhoneNumber ( const std::string & phoneNumber ) ;

Sets the user's phone number.

static void setFacebookUserId ( const std::string & facebookUserId ) ;

Set user's Facebook ID.

static void setTwitterUserId ( const std::string & twitterUserId ) ;

Set user's Twitter ID.

static void setGoogleUserId ( const std::string & googleUserId ) ;

Set user's Google ID.

static void setAge ( int userAge ) ;

Sets the user's age.

static void setGender ( Gender userGender ) ;

Sets the user's gender.

static void setLatitude ( double latitude , double longitude ) ;

Sets the user's location.

static void setLatitude ( double latitude ,
                          double longitude ,
                          double altitude ) ;

Sets the user's location including altitude.

static void setAppAdTracking ( bool enable ) ;

Set app-level ad-tracking.

static void setPayingUser ( bool isPayingUser ) ;

Set whether the user is generating revenue for the app or not. If measureEvent is called with a non-zero revenue, this is automatically set to YES.

static void setPreloadData ( const TunePreloadData & preloadData ) ;

Sets publisher information for attribution.

@function setPreloadDataForScript for Js / Lua
@function setPreloadData for cpp
static void setPreloadDataForScript ( const std::string & jsonString ) ;
SDKBOX_DEPRECATED ( "tuneId" ) static std::string matId ( ) ;

Get the MAT ID for this installation (mat_id).

@return MAT ID
static std::string tuneId ( ) ;

Get the Tune ID for this installation.

@return Tune ID
static std::string openLogId ( ) ;

Get the MAT log ID for the first app open (open_log_id).

@return open log ID
static bool isPayingUser ( ) ;

Get whether the user is revenue-generating.

@return YES if the user has produced revenue, NO if not
static void measureSession ( ) ;

To be called when an app opens; typically in the AppDelegate::applicationWillEnterForeground() event.

static void measureEventName ( const std::string & eventName ) ;

Record an event for an Event Name.

static void measureEventId ( int eventId ) ;

Record an event by providing the equivalent Event ID defined on the MobileAppTracking dashboard.

static void measureEvent ( const TuneEvent & event ) ;

Record an event with a MATEvent.

@function measureEventForScript for Js / Lua
@function measureEvent for cpp
static void measureEventForScript ( const std::string & jsonString ) ;
static void setUseCookieTracking ( bool enable ) ;

Sets whether or not to use cookie based tracking.

static void setRedirectUrl ( const std::string & redirectUrl ) ;

Sets a url to be used with app-to-app tracking so that the sdk can open the download (redirect) url. This is used in conjunction with the setTracking:advertiserId:offerId:publisherId:redirect: method.

static void startAppToAppTracking ( const std::string & targetAppPackageName ,
                                    const std::string & targetAppAdvertiserId ,
                                    const std::string & targetAdvertiserOfferId ,
                                    const std::string & targetAdvertiserPublisherId ,
                                    bool shouldRedirect ) ;

Start an app-to-app tracking session on the MAT server.

successfully created. See setRedirectUrl:.
static void applicationDidOpenURL ( const std::string & urlString ,
                                    const std::string & sourceApplication ) ;

Record the URL and Source when an application is opened via a URL scheme. This typically occurs during OAUTH or when an app exits and is returned to via a URL. The data will be sent to the HasOffers server when the next measureXXX method is called so that a Re-Engagement can be recorded.

static void setDeepLink ( const std::string & deepLinkUrl ) ;

Record the URL and Source when an application is opened via a URL scheme.

Listeners

void onMobileAppTrackerEnqueuedActionWithReferenceId ( const std::string & referenceId );
void onMobileAppTrackerDidSucceedWithData ( const std::string & data );
void onMobileAppTrackerDidFailWithError ( const std::string & errorString );
void onMobileAppTrackerDidReceiveDeeplink ( const std::string & deeplink ,
                                            bool timeout );
void onMobileAppTrackerDidFailDeeplinkWithError ( const std::string & errorString );

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 the Tune bundle into your Xcode project, check Copy items if needed when adding frameworks:

sdkbox.framework

PluginTune.framework

MobileAppTracker.framework

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

CoreTelephony.framework

Security.framework

SystemConfiguration.framework

AdSupport.framework

iAd.framework

MobileCoreServices.framework

StoreKit.framework

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.

PluginTune.jar

sdkbox.jar

MobileAppTracker-3.9.jar

Copy jni libs

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

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

To enable hardware acceleration in your application tag. This tag is optional on newer SDK versions and doesn't work on version 2.3.3.

<android:hardwareAccelerated="true" />

It is also necessary to create an application tag:

<application ... >
    <receiver android:name="com.mobileapptracker.Tracker">
        <intent-filter>
            <action android:name="com.android.vending.INSTALL_REFERRER" />
        </intent-filter>
    </receiver>
    <meta-data android:name="com.google.android.gms.version"
               android:value="@integer/google_play_services_version" />
</application>

Edit Android.mk

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

Add additional requirements to LOCAL_WHOLE_STATIC_LIBRARIES:

LOCAL_WHOLE_STATIC_LIBRARIES += PluginTune
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, ./plugintune)

This means that your ordering should look similar to this:

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

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 AppActivity.java

Plugin >= 2.4.0.3

  1. Find the AppActivity.java
find . -name "AppActivity.java"
  1. Replace extends Cocos2dxActivity with extends com.sdkbox.plugin.SDKBoxActivity

Example of the directory where the AppActivity.java file is located:

cpp
  - proj.android/src/org/cocos2dx/cpp/AppActivity.java
  - proj.android-studio/app/src/org/cocos2dx/cpp/AppActivity.java
  - proj.android/app/src/org/cocos2dx/cpp/AppActivity.java ( from cocos2d-x 3.17)

lua
  - frameworks/runtime-src/proj.android/src/org/cocos2dx/lua/AppActivity.java
  - frameworks/runtime-src/proj.android-studio/app/src/org/cocos2dx/lua/AppActivity.java
  - frameworks/runtime-src/proj.android/app/src/org/cocos2dx/lua/AppActivity.java (from cocos2d-x 3.17)

js
  - frameworks/runtime-src/proj.android/src/org/cocos2dx/javascript/AppActivity.java
  - frameworks/runtime-src/proj.android/app/src/org/cocos2dx/javascript/AppActivity.java ( from cocos2d-x 3.17)

Plugin < 2.4.0.3

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-14
+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=proguard.cfg
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
#   public *;
#}

# cocos2d-x
-keep public class org.cocos2dx.** { *; }
-dontwarn org.cocos2dx.**
-keep public class com.chukong.** { *; }
-dontwarn com.chukong.**

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

-keep class com.google.protobuf.** { *; }
-dontwarn com.google.protobuf.**

-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 public class com.sdkbox.** { *; }
-dontwarn com.sdkbox.**

#tune
-keep public class com.mobileapptracker.** {
    public *;
}

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