NLDClient-yudde/ProjectNLD/Assets/Code/Scripts/HotUpdate/Device/DeviceIdHandle.cs

84 lines
2.4 KiB
C#
Raw Normal View History

2025-11-03 15:37:16 +08:00
using System.Collections;
using System.Collections.Generic;
2025-11-17 12:40:48 +08:00
using System.Runtime.ConstrainedExecution;
2025-11-03 15:37:16 +08:00
using UnityEngine;
2025-11-17 13:04:57 +08:00
public class DeviceIdHandle
2025-11-03 15:37:16 +08:00
{
private static DeviceIdHandle _instance;
private AndroidJavaObject oaidActivity;
2025-11-17 12:40:48 +08:00
private string oaid = "";
private string imei = "";
public string Oaid => oaid;
public string Imei => imei;
2025-11-14 20:03:39 +08:00
class OaidCallbackProxy : AndroidJavaProxy
{
public OaidCallbackProxy() : base("com.example.oaidtest2.DemoHelper$OaidCallback") { }
void onResult(int code, string msg, string oaid, long durationMs)
{
if (code == 0)
{
Debug.Log($"OAID: {oaid} (耗时: {durationMs}ms)");
2025-11-17 12:40:48 +08:00
DeviceIdHandle.Instance.oaid = oaid;
2025-11-14 20:03:39 +08:00
}
else
{
Debug.LogError($"OAID 获取失败: {msg}");
}
}
}
2025-11-17 12:40:48 +08:00
class IMEICallbackProxy : AndroidJavaProxy
{
public IMEICallbackProxy() : base("com.example.oaidtest2.DemoHelper$ImeiCallback") { }
void onResult(string imei)
{
DeviceIdHandle.Instance.imei = imei;
}
}
2025-11-03 15:37:16 +08:00
public static DeviceIdHandle Instance
{
get
{
if (_instance is null)
{
2025-11-17 13:04:57 +08:00
_instance = new DeviceIdHandle();
2025-11-03 15:37:16 +08:00
}
return _instance;
}
}
2025-11-17 12:40:48 +08:00
public void Initialize()
2025-11-12 19:29:37 +08:00
{
#if UNITY_ANDROID && !UNITY_EDITOR
2025-11-14 12:19:27 +08:00
//获取当前 Android Activity 并调用插件初始化接口
2025-11-12 19:29:37 +08:00
try
{
2025-11-17 12:40:48 +08:00
var unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
var activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
var appContext = activity.Call<AndroidJavaObject>("getApplicationContext");
var helperClass = new AndroidJavaClass("com.example.oaidtest2.DemoHelper");
var helper = helperClass.CallStatic<AndroidJavaObject>("getInstance", appContext);
2025-11-12 19:29:37 +08:00
2025-11-17 12:40:48 +08:00
helper.Call("getOAID", new OaidCallbackProxy());
2025-11-12 19:29:37 +08:00
2025-11-17 12:40:48 +08:00
// 调用 Android 的 GetIMEI 方法
helper.Call("getImei", new IMEICallbackProxy());
2025-11-12 19:29:37 +08:00
}
catch (System.Exception e)
{
2025-11-17 12:40:48 +08:00
Debug.LogError("GetDeviceId failed: " + e);
2025-11-12 19:29:37 +08:00
}
#else
2025-11-17 12:40:48 +08:00
Debug.Log("GetDeviceID: Initialized (editor or non-Android). Android call skipped.");
2025-11-12 19:29:37 +08:00
#endif
2025-11-03 15:37:16 +08:00
}
}