Unity 数据统计SDK TalkingData

官网链接:http://www.talkingdata.com/

进入官方给出的demo网页统计

API使用文档:http://doc.talkingdata.com/posts/65#%E5%BF%AB%E9%80%9F%E9%9B%86%E6%88%90-%E9%9B%86%E6%88%90%E6%A3%80%E6%9F%A5%E5%88%97%E8%A1%A8

下面是配置流程

第一步:常规注册登录



创建游戏产品

填写游戏名称类型等

下载对应平台的SDK。点击对应图标即可进入

配置需要下载的定制SDK文件

点击完成下一步


然后会出现这个界面

一会就会收到talkingdata发来的sdk压缩包,下载解压

主要得到两个文件 android的jar和ios的.a文件

分别把这两个文件放到unity的文件夹中:

  • Android 平台 将最新的 .jar 文件复制到 Assets/Plugins/Android 目录下
  • iOS 平台 将最新的 .a 文件复制到 Assets/Plugins/iOS 目录下

    进入官方给出的github上面的网址:https://github.com/TalkingData/GameAnalytics_SDK_Unity

把下载的文件放到unity响应的目录中


把网站上对应的AppID替换掉


挂上脚本运行

打包运行,只有真机上才好使


显示触发的各种事件

注意IOS需要添加依赖框架



添加权限,方便其他同事查阅


更新数据时间

OVER,大功告成!!!

在官方示例的基础带上添加了对应的注释和用法,在官网都可以找到

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using System.Threading;

public class CustomDemoScript : MonoBehaviour
{

    int index = 1;
    int level = 1;
    string gameserver = "";
    TDGAAccount account;

    const int left = 90;
    const int height = 50;
    const int top = 60;
    int width = Screen.width - left * 2;
    const int step = 60;

    #region
    void OnGUI()
    {

        int i = 0;
        GUI.Box(new Rect(10, 10, Screen.width - 20, Screen.height - 20), "Demo Menu");

        if (GUI.Button(new Rect(left, top + step * i++, width, height), "创建用户唯一标识"))
        {
            account = TDGAAccount.SetAccount(TalkingDataGA.GetDeviceId());
            index++;
        }

        if (GUI.Button(new Rect(left, top + step * i++, width, height), "用户等级提升1级"))
        {
            if (account != null)
            {
                account.SetLevel(level++);
            }
        }

        if (GUI.Button(new Rect(left, top + step * i++, width, height), "传入玩家登入的区服"))
        {
            if (account != null)
            {
                gameserver = "国服01";
                account.SetGameServer(gameserver);
            }
        }


        if (GUI.Button(new Rect(left, top + step * i++, width, height), "Charge Request 10"))
        {
            TDGAVirtualCurrency.OnChargeRequest("order01", "iap", 10, "CH", 10, "PT");
        }

        if (GUI.Button(new Rect(left, top + step * i++, width, height), "Charge Success 10"))
        {
            TDGAVirtualCurrency.OnChargeSuccess("order01");
        }

        if (GUI.Button(new Rect(left, top + step * i++, width, height), "Reward 100"))
        {
            TDGAVirtualCurrency.OnReward(100, "reason");
        }

        if (GUI.Button(new Rect(left, top + step * i++, width, height), "任务开始"))
        {
            TDGAMission.OnBegin("任务001");
        }

        if (GUI.Button(new Rect(left, top + step * i++, width, height), " 任务完成"))
        {
            TDGAMission.OnCompleted("任务001");
        }

        if (GUI.Button(new Rect(left, top + step * i++, width, height), "Item Purchase 10"))
        {
            TDGAItem.OnPurchase("itemid001", 10, 10);
        }

        if (GUI.Button(new Rect(left, top + step * i++, width, height), "Item Use 1"))
        {
            TDGAItem.OnUse("itemid001", 1);
        }

        if (GUI.Button(new Rect(left, top + step * i++, width, height), "自定义事件"))
        {
            Dictionary dic = new Dictionary();
            dic.Add("StartApp" + "StartAppTime", "startAppMac" + "#" + "02/01/2013 09:52:24");
            dic.Add("IntValue", 1);
            TalkingDataGA.OnEvent("自定义事件Str01", dic);
        }
    }
    #endregion
    void Start()
    {
        Debug.Log("start...!!!!!!!!!!");
#if UNITY_IPHONE
#if UNITY_5
        UnityEngine.iOS.NotificationServices.RegisterForNotifications(
            UnityEngine.iOS.NotificationType.Alert |
            UnityEngine.iOS.NotificationType.Badge |
            UnityEngine.iOS.NotificationType.Sound);
#else
        NotificationServices.RegisterForRemoteNotificationTypes(
            RemoteNotificationType.Alert |
            RemoteNotificationType.Badge |
            RemoteNotificationType.Sound);
#endif
#endif
        TalkingDataGA.OnStart("C2E1B36A7A12412A88E13BED666D22D8", "想什么渠道就什么渠道渠道,应用宝,豌豆荚随便");
        account = TDGAAccount.SetAccount("User01");//必须设置
    }

    void Update()
    {
        if (Input.GetKey(KeyCode.Escape))
        {
            Application.Quit();
        }
#if UNITY_IPHONE
        TalkingDataGA.SetDeviceToken();
        TalkingDataGA.HandleTDGAPushMessage();
#endif
    }

    void OnDestroy()
    {
        TalkingDataGA.OnEnd();
        Debug.Log("onDestroy");
    }

    void Awake()
    {
        Debug.Log("Awake");
    }

    void OnEnable()
    {
        Debug.Log("OnEnable");
    }

    void OnDisable()
    {
        Debug.Log("OnDisable");
    }
}

// SDK Version: 3.2.14

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System;
using System.Threading;

public class TalkingDataGA {
#if UNITY_IPHONE
    [DllImport ("__Internal")]
    private static extern void tdgaOnStart(string appId, string channelId);
    
    [DllImport ("__Internal")]
    private static extern void tdgaOnEvent(string eventId, string []keys, string []stringValues, double []numberValues, int count);
    
    [DllImport ("__Internal")]
    private static extern string tdgaGetDeviceId();
    
    [DllImport ("__Internal")]
    private static extern void tdgaSetSDKFramework(int tag);
    
    [DllImport ("__Internal")]
    private static extern void tdgaSetVerboseLogDisabled();
    
    [DllImport ("__Internal")]
    private static extern void tdgaSetDeviceToken(string deviceToken);
    
    [DllImport ("__Internal")]
    private static extern void tdgaHandlePushMessage(string message);
    
    private static bool hasTokenBeenObtained = false;
#elif UNITY_ANDROID
    //init static class --save memory/space
    private static AndroidJavaClass agent;
    private static AndroidJavaClass unityClass;
    
    private static string JAVA_CLASS = "com.tendcloud.tenddata.TalkingDataGA";
    private static string UNTIFY_CLASS = "com.unity3d.player.UnityPlayer";

    public static void AttachCurrentThread() {
        AndroidJNI.AttachCurrentThread();
    }
    
    public static void DetachCurrentThread() {
        AndroidJNI.DetachCurrentThread();
    }
#endif
    private static string deviceId = null;

    public static string GetDeviceId() {
        //if the platform is real device
        if (deviceId == null && Application.platform != RuntimePlatform.OSXEditor && Application.platform != RuntimePlatform.WindowsEditor) {
#if UNITY_IPHONE
            deviceId = tdgaGetDeviceId();
#elif UNITY_ANDROID
            if (agent == null) {
                agent = new AndroidJavaClass(JAVA_CLASS);
            }
            AndroidJavaObject activity = unityClass.GetStatic("currentActivity");
            deviceId = agent.CallStatic("getDeviceId", activity);
#elif UNITY_WP8
            deviceId = TalkingDataGAWP.TalkingDataGA.getDeviceID();
#endif
        }
        return deviceId;
    }
    
    public static void OnStart(string appID, string channelId) {
        //if the platform is real device
        if (Application.platform != RuntimePlatform.OSXEditor && Application.platform != RuntimePlatform.WindowsEditor) {
#if UNITY_IPHONE
//          tdgaSetSDKFramework(2);
            tdgaOnStart(appID, channelId);
#elif UNITY_ANDROID
            AndroidJavaClass dz = new AndroidJavaClass("com.tendcloud.tenddata.game.dz");
            dz.SetStatic("a", 2);
            if (agent == null) {
                agent = new AndroidJavaClass(JAVA_CLASS);
            }
            // agent.SetStatic("sPlatformType", 2);
            unityClass = new AndroidJavaClass(UNTIFY_CLASS);
            AndroidJavaObject activity = unityClass.GetStatic("currentActivity");
            agent.CallStatic("init", activity, appID, channelId);
            agent.CallStatic("onResume", activity);
#elif UNITY_WP8
            TalkingDataGAWP.TalkingDataGA.init(appID, channelId);
#endif
        }
    }
    
    public static void OnEnd() {
        if (Application.platform != RuntimePlatform.OSXEditor && Application.platform != RuntimePlatform.WindowsEditor) {
#if UNITY_ANDROID
            if (agent != null) {
                AndroidJavaObject activity = unityClass.GetStatic("currentActivity");
                agent.CallStatic("onPause", activity);
                agent = null;
                unityClass = null;
            }
#endif
        }
    }
    
    public static void OnKill() {
        if (Application.platform != RuntimePlatform.OSXEditor && Application.platform != RuntimePlatform.WindowsEditor) {
#if UNITY_ANDROID
            if (agent != null) {
                AndroidJavaObject activity = unityClass.GetStatic("currentActivity");
                agent.CallStatic("onKill", activity);
                agent = null;
                unityClass = null;
            }
#endif
        }
    }
    /// 
    /// 自定义事件
    /// 开发者可以自行定义eventId,在游戏中需要追踪的位置进行调用,注意eventId中仅限使用中英文字符、数字和下划线,不要加空格或其他的转义字符
    /// 除了可以统计某自定义eventId的触发次数,还可以通过key-value参数来对当时触发事件时的属性进行描述。如定义 eventId 为玩家死亡事件,可通过 key-value 添加死亡时关卡、死亡时等级、死亡时携带金币等属性。
    /// 每款游戏可定义最多10000个不同eventId,每个eventId下,可以支持100种 不同 key 的 1000种不同 value 取值(NSString 类型),但是每次事件发生时最多只能同时附带 50 种不同 key
    /// 
    /// 自定义事件名称,最多支持 32 个字符
    /// key 类型必须是string,一次事件最多只支持 50 个参数。如果 value 为 string,
    /// Game Analytics 会统计每种 value 出现的次数;如果为 number 类型,那么 Game Analytics 会统计 value 的总和。
    public static void OnEvent(string actionId, Dictionary parameters) {
        if (Application.platform != RuntimePlatform.OSXEditor && Application.platform != RuntimePlatform.WindowsEditor) {
#if UNITY_IPHONE
            if (parameters != null && parameters.Count > 0) {
                int count = parameters.Count;
                string []keys = new string[count];
                string []stringValues = new string[count];
                double []numberValues = new double[count];
                int index = 0;
                foreach (KeyValuePair kvp in parameters) {
                    if (kvp.Value is string) {
                        keys[index] = kvp.Key;
                        stringValues[index] = (string)kvp.Value;
                    } else {
                        try {
                            double tmp = System.Convert.ToDouble(kvp.Value);
                            numberValues[index] = tmp;
                            keys[index] = kvp.Key;
                        } catch(System.Exception) {
                            count--;
                            continue;
                        }
                    }
                    index++;
                }
                
                tdgaOnEvent(actionId, keys, stringValues, numberValues, count);
            } else {
                tdgaOnEvent(actionId, null, null, null, 0);
            }
#elif UNITY_ANDROID
            if (parameters != null && parameters.Count > 0) {
                int count = parameters.Count;
                AndroidJavaObject map = new AndroidJavaObject("java.util.HashMap", count);
                IntPtr method_Put = AndroidJNIHelper.GetMethodID(map.GetRawClass(), 
                        "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
                object[] args = new object[2];
                foreach (KeyValuePair kvp in parameters) {
                    args[0] = new AndroidJavaObject("java.lang.String", kvp.Key);
                    if (typeof(System.String).IsInstanceOfType(kvp.Value)) {
                        args[1] = new AndroidJavaObject("java.lang.String", kvp.Value);
                    } else {
                        args[1] = new AndroidJavaObject("java.lang.Double", ""+kvp.Value);
                    }
                    AndroidJNI.CallObjectMethod(map.GetRawObject(), method_Put, AndroidJNIHelper.CreateJNIArgArray(args));
                }
                
                if (agent != null) {
                    agent.CallStatic("onEvent", actionId, map);
                }
            } else {
                if (agent != null) {
                    agent.CallStatic("onEvent", actionId, null);
                }
            }
#elif UNITY_WP8
                TalkingDataGAWP.TalkingDataGA.onEvent(actionId, parameters);
#endif
        }
    }
    
    public static void SetVerboseLogDisabled() {
        if (Application.platform != RuntimePlatform.OSXEditor && Application.platform != RuntimePlatform.WindowsEditor) {
#if UNITY_IPHONE
            tdgaSetVerboseLogDisabled();
#elif UNITY_ANDROID
            if (agent == null) {
                agent = new AndroidJavaClass(JAVA_CLASS);
            }
            agent.CallStatic("setVerboseLogDisabled");
#elif UNITY_WP8
#endif
        }
    }

#if UNITY_IPHONE
#if UNITY_5
    public static void SetDeviceToken() {
        if (!hasTokenBeenObtained) {
            byte[] byteToken = UnityEngine.iOS.NotificationServices.deviceToken;
            if(byteToken != null) {
                string deviceToken = System.BitConverter.ToString(byteToken).Replace("-","");
                tdgaSetDeviceToken(deviceToken);
                hasTokenBeenObtained = true;
            }
        }
    }
    
    public static void HandlePushMessage() {
        UnityEngine.iOS.RemoteNotification[] notifications = UnityEngine.iOS.NotificationServices.remoteNotifications;
        if (notifications != null) {
            UnityEngine.iOS.NotificationServices.ClearRemoteNotifications();
            foreach (UnityEngine.iOS.RemoteNotification rn in notifications) {
                foreach (DictionaryEntry de in rn.userInfo) {
                    if (de.Key.ToString().Equals("sign")) {
                        string sign = de.Value.ToString();
                        tdgaHandlePushMessage(sign);
                    }
                }
            }
        }
    }
#else
    public static void SetDeviceToken() {
        if (!hasTokenBeenObtained) {
            byte[] byteToken = NotificationServices.deviceToken;
            if(byteToken != null) {
                string deviceToken = System.BitConverter.ToString(byteToken).Replace("-","");
                tdgaSetDeviceToken(deviceToken);
                hasTokenBeenObtained = true;
            }
        }
    }

    public static void HandlePushMessage() {
        RemoteNotification[] notifications = NotificationServices.remoteNotifications;
        if (notifications != null) {
            NotificationServices.ClearRemoteNotifications();
            foreach (RemoteNotification rn in notifications) {
                foreach (DictionaryEntry de in rn.userInfo) {
                    if (de.Key.ToString().Equals("sign")) {
                        string sign = de.Value.ToString();
                        tdgaHandlePushMessage(sign);
                    }
                }
            }
        }
    }
#endif
#endif
}

你可能感兴趣的:(Unity 数据统计SDK TalkingData)