Unity安卓生成设备唯一id

目标:生成唯一id,重启后生成仍旧相同。
其实可以使用GAID等来源于其他SDK的唯一id,但是为了一个UUID而接入一些SDK,好像也不太对
这里参考网上一些内容,通过设备相关信息,生成UUID。作为唯一id

相关代码和aar已经打包成一份package了:代码+样例下载

android的代码:

    public String GetSerial()
    {
        String serial = "";
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                serial = Build.getSerial();
            } else {
                serial = Build.SERIAL;
            }
            return serial;
        } catch (Exception exception) {
            //serial需要一个初始化
            serial = "serial"; // 随便一个初始化
            return serial;
        }
    }
    
 public String GetUUIDCustom(String serial){
        String m_szDevIDShort = "35" +
                Build.BOARD.length()%10+ Build.BRAND.length()%10 +

                Build.CPU_ABI.length()%10 + Build.DEVICE.length()%10 +

                Build.DISPLAY.length()%10 + Build.HOST.length()%10 +

                Build.ID.length()%10 + Build.MANUFACTURER.length()%10 +

                Build.MODEL.length()%10 + Build.PRODUCT.length()%10 +

                Build.TAGS.length()%10 + Build.TYPE.length()%10 +

                Build.USER.length()%10 ; //13 位
        return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
    }

Unity的代码:

	/// 
	/// 根据设备信息生成一个UUID,如果能拿到serial就用serial生成,如果没拿到那就用deviceUniqueIdentifier生成
	/// 
	/// 
	static public string DeviceUUID()
	{

#if UNITY_ANDROID
		if (instance == null)
		{
			instance = new UUIDHelper();
			instance.Init();
		}
		if(serial == "serial")
		{
			string unity_devid = UnityDeviceId();
			return CustomUUID(unity_devid);
		}
		string uuid = instance.java_obj.Call<string>("GetUUID");
		uuid = uuid.Replace("-", "");
		return uuid;
#else
		return SystemInfo.deviceUniqueIdentifier;
#endif
	}

你可能感兴趣的:(unity,android,unity,android,游戏引擎)