Unity 接入

最近更新时间:2024-07-26 14:53:01

我的收藏
接入准备
获取 SDK 文件 并复制到 Unity 项目的 Assets/Plugins/Android目录中
初始化 HTTPDNS。代码示例如下:
SDK 初始化配置信息,具体请参见 Android SDK 接入
private static AndroidJavaObject sHttpDnsObj;
public static void Init() {
AndroidJavaClass unityPlayerClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
if (unityPlayerClass == null) {
return;
}
AndroidJavaObject activityObj = unityPlayerClass.GetStatic<AndroidJavaObject>("currentActivity");
if (activityObj == null) {
return;
}
AndroidJavaObject contextObj = activityObj.Call<AndroidJavaObject>("getApplicationContext");
// 初始化 HTTPDNS
AndroidJavaObject httpDnsClass = new AndroidJavaObject("com.tencent.msdk.dns.MSDKDnsResolver");
if (httpDnsClass == null) {
return;
}
sHttpDnsObj = httpDnsClass.CallStatic<AndroidJavaObject>("getInstance");
if (sHttpDnsObj == null) {
return;
}
// V4.0.0开始(推荐使用)
AndroidJavaObject dnsConfigBuilder = new AndroidJavaObject("com.tencent.msdk.dns.DnsConfig$Builder");
dnsConfigBuilder.Call<AndroidJavaObject>("dnsId", "XXX");
dnsConfigBuilder.Call<AndroidJavaObject>("dnsIp", "XXX");
dnsConfigBuilder.Call<AndroidJavaObject>("dnsKey", "XXX");
// 其他配置信息...
AndroidJavaObject dnsConfig = dnsConfigBuilder.Call<AndroidJavaObject>("build");
sHttpDnsObj.Call("init", contextObj, dnsConfig);
// V4.0.0之前
sHttpDnsObj.Call("init", contextObj, appkey, dnsid, dnskey, dnsIp, debug, timeout);
}
调用 getAddrByName 接口解析域名。代码示例如下:
// 该操作建议在子线程中或使用 Coroutine 处理
// 注意在子线程中调用需要在调用前后做 AttachCurrentThread 和 DetachCurrentThread 处理
public static string GetHttpDnsIP(string url) {
string ip = string.Empty;
AndroidJNI.AttachCurrentThread(); // 子线程中调用需要加上
// 解析得到 IP 配置集合
string ips = sHttpDnsObj.Call<string>("getAddrByName", url);
AndroidJNI.DetachCurrentThread(); // 子线程中调用需要加上
if (null != ips) {
string[] ipArr = ips.Split(';');
if (2 == ipArr.Length && !"0".Equals(ipArr[0]))
ip = ipArr[0];
}
return ip;
}
IP 直连 HTTPS 证书校验,请参见 unity官方指引。代码示例如下:
UnityWebRequest www = UnityWebRequest.Get(url);
www.certificateHandler = new CertHandler();
yield return www.SendWebRequest();
// CertHandler是一个自定义的证书处理器类,重写ValidateCertificate方法,实现自定义的证书验证逻辑。
public class CertHandler : CertificateHandler
{
protected override bool ValidateCertificate(byte[] certificateData)
{
X509Certificate2 certificate = new X509Certificate2(certificateData);
X509Certificate2Collection collection = new X509Certificate2Collection();
collection.Import(Application.dataPath + "/Certificates/server.cer");
return certificate.Issuer == collection[0].Issuer;
}
}