Files
BabyVideo/Assets/Scripts/Utils/PlatformInfo.cs
2026-02-12 22:15:15 +08:00

107 lines
3.7 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using UnityEngine;
using SystemInfo = UnityEngine.Device.SystemInfo;
namespace NBF
{
public static class PlatformInfo
{
public static string GetAndroidID()
{
string androidId = string.Empty;
#if UNITY_EDITOR
if (string.IsNullOrEmpty(androidId))
{
androidId = SystemInfo.deviceUniqueIdentifier;
}
#elif UNITY_ANDROID
// 只在 Android 平台上执行此操作
if (Application.platform == RuntimePlatform.Android)
{
try
{
using (AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
{
AndroidJavaObject currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
AndroidJavaObject contentResolver =
currentActivity.Call<AndroidJavaObject>("getContentResolver");
AndroidJavaClass secureSettings = new AndroidJavaClass("android.provider.Settings$Secure");
androidId = secureSettings.CallStatic<string>("getString", contentResolver, "android_id");
}
}
catch (System.Exception e)
{
Debug.LogError("Error while fetching Android ID: " + e.Message);
}
}
else
{
Debug.LogError("Not running on Android platform.");
}
#elif UNITY_IOS
androidId = SystemInfo.deviceUniqueIdentifier;
#endif
Debug.LogWarning($"androidId={androidId}");
return androidId;
}
public static string GetDeviceModel()
{
string deviceModel = string.Empty;
#if UNITY_EDITOR
// 在编辑器中使用 SystemInfo
deviceModel = SystemInfo.deviceModel;
#elif UNITY_ANDROID
if (Application.platform == RuntimePlatform.Android)
{
try
{
// 方法1使用 SystemInfo.deviceModel推荐最简单
deviceModel = SystemInfo.deviceModel;
// 方法2通过 Android API 获取更详细的信息(可选)
/*
using (AndroidJavaClass buildClass = new AndroidJavaClass("android.os.Build"))
{
string manufacturer = buildClass.GetStatic<string>("MANUFACTURER");
string model = buildClass.GetStatic<string>("MODEL");
string product = buildClass.GetStatic<string>("PRODUCT");
string device = buildClass.GetStatic<string>("DEVICE");
// 可以根据需要组合不同的信息
deviceModel = $"{manufacturer} {model}";
// 或者更详细的deviceModel = $"{manufacturer} {model} (Product: {product}, Device: {device})";
}
*/
}
catch (System.Exception e)
{
Debug.LogError("Error while fetching device model: " + e.Message);
deviceModel = SystemInfo.deviceModel; // 失败时回退到 SystemInfo
}
}
else
{
deviceModel = SystemInfo.deviceModel;
}
#elif UNITY_IOS
// iOS平台
deviceModel = SystemInfo.deviceModel;
// 如果需要获取更友好的设备名称(如 "iPhone 14 Pro" 而不是 "iPhone15,2"
if (Application.platform == RuntimePlatform.IPhonePlayer)
{
deviceModel = UnityEngine.iOS.Device.generation.ToString();
}
#else
// 其他平台
deviceModel = SystemInfo.deviceModel;
#endif
Debug.LogWarning($"Device Model: {deviceModel}");
return deviceModel;
}
}
}