判断设备是否连接了特定的网络
- 1.Unity 脚本
- 2.Unity AndroidManifest.xml文件
- ①改个设置
- ②补充权限语句
1.Unity 脚本
using UnityEngine;
using System.Collections;
using System.Diagnostics;
using Debug = UnityEngine.Debug;
using UnityEngine.UI;#if UNITY_ANDROID && !UNITY_EDITOR
using UnityEngine.Android;
#endifpublic class WiFiChecker : MonoBehaviour
{public string targetWiFiName = "YourWiFiName";public float checkInterval = 5f;private string currentSSID = "Unknown";private bool isInitialized = false;public GameObject ObjwifiTip;public Text TipText;void Start(){InitializeWiFiChecker();StartCoroutine(CheckWiFiPeriodically());}private void InitializeWiFiChecker(){
#if UNITY_ANDROID && !UNITY_EDITOR// 检查并请求Android权限if (!Permission.HasUserAuthorizedPermission(Permission.FineLocation)){Debug.Log("请求网络访问权限...");Permission.RequestUserPermission(Permission.FineLocation);}
#endifisInitialized = true;}private IEnumerator CheckWiFiPeriodically(){// 等待初始化完成yield return new WaitUntil(() => isInitialized);while (true){yield return new WaitForSeconds(checkInterval);yield return StartCoroutine(GetCurrentSSIDCoroutine());}}private IEnumerator GetCurrentSSIDCoroutine(){
#if UNITY_EDITOR// 在编辑器中模拟//currentSSID = GetWindowsWiFiSSID();currentSSID = "Editor_Simulation_Mode";
#elif UNITY_STANDALONE_WIN// Windows平台currentSSID = GetWindowsWiFiSSID();
#elif UNITY_STANDALONE_OSX// macOS平台currentSSID = GetMacWiFiSSID();
#elif UNITY_ANDROID// Android平台currentSSID = GetAndroidWiFiSSID();
#elsecurrentSSID = "Unsupported Platform";
#endifUseName(currentSSID);yield return null;}private string GetWindowsWiFiSSID(){try{Process process = new Process();process.StartInfo.FileName = "netsh";process.StartInfo.Arguments = "wlan show interfaces";process.StartInfo.UseShellExecute = false;process.StartInfo.RedirectStandardOutput = true;process.StartInfo.CreateNoWindow = true;process.Start();string output = process.StandardOutput.ReadToEnd();process.WaitForExit();// 解析SSIDstring[] lines = output.Split('\n');foreach (string line in lines){if (line.Trim().StartsWith("SSID")){int colonIndex = line.IndexOf(':');if (colonIndex > 0){string ssid = line.Substring(colonIndex + 1).Trim();if (!string.IsNullOrEmpty(ssid) && !ssid.Contains("null")){return ssid;}}}}return "Not Connected";}catch (System.Exception e){Debug.LogWarning($"获取Windows WiFi SSID失败: {e.Message}");return "Error";}}private string GetMacWiFiSSID(){try{Process process = new Process();process.StartInfo.FileName = "/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport";process.StartInfo.Arguments = "-I";process.StartInfo.UseShellExecute = false;process.StartInfo.RedirectStandardOutput = true;process.StartInfo.CreateNoWindow = true;process.Start();string output = process.StandardOutput.ReadToEnd();process.WaitForExit();// 解析SSIDstring[] lines = output.Split('\n');foreach (string line in lines){if (line.Trim().StartsWith("SSID:")){int colonIndex = line.IndexOf(':');if (colonIndex > 0){return line.Substring(colonIndex + 1).Trim();}}}return "Not Connected";}catch (System.Exception e){Debug.LogWarning($"获取macOS WiFi SSID失败: {e.Message}");return "Error";}}#if UNITY_ANDROID && !UNITY_EDITORprivate string GetAndroidWiFiSSID(){try{// 检查权限if (!Permission.HasUserAuthorizedPermission(Permission.FineLocation)){Debug.LogWarning("需要网络访问权限才能获取WiFi信息");return "Permission Required";}using (AndroidJavaObject activity = new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic<AndroidJavaObject>("currentActivity")){using (AndroidJavaObject wifiManager = activity.Call<AndroidJavaObject>("getSystemService", "wifi")){using (AndroidJavaObject wifiInfo = wifiManager.Call<AndroidJavaObject>("getConnectionInfo")){string ssid = wifiInfo.Call<string>("getSSID");if (string.IsNullOrEmpty(ssid) || ssid == "<unknown ssid>"){return "Not Connected";}// 移除可能存在的引号if (ssid.StartsWith("\"") && ssid.EndsWith("\"")){ssid = ssid.Substring(1, ssid.Length - 2);}return ssid;}}}}catch (System.Exception e){Debug.LogWarning($"获取Android WiFi SSID失败: {e.Message}");return "Error";}}
#elseprivate string GetAndroidWiFiSSID(){// 在编辑器中模拟Android行为return "Android_Simulated_WiFi";}
#endifpublic void UseName(string name){if (ObjwifiTip != null && ObjwifiTip.activeSelf){return;}if (name == targetWiFiName){Debug.Log($"✅ 网络正确,当前WiFi:{name}");// 网络正确时的逻辑}else{string message = "";if (name == "Error" || name == "Permission Required"){message = $"检测失败: {name}";}else if (name == "Not Connected"){message = "未连接到任何WiFi网络";}else if (name == "Editor_Simulation_Mode"){message = "编辑器模拟模式 - 请在真机或PC上运行";}else if (name == "Unsupported Platform"){message = "不支持的平台";}else{message = $"网络错误,请检查网络后重启软件,当前WiFi:{name}";}Debug.Log(message);if (ObjwifiTip != null && TipText != null){OpenTipPage(message);}}}public void OpenTipPage(string t){if (ObjwifiTip != null){ObjwifiTip.SetActive(true);}if (TipText != null){TipText.text = t;}}public bool IsOnTargetWiFi(){return currentSSID.Equals(targetWiFiName, System.StringComparison.OrdinalIgnoreCase);}public void ManualCheck(){StartCoroutine(GetCurrentSSIDCoroutine());}//// 添加一个关闭提示页面的方法//public void CloseTipPage()//{// if (ObjwifiTip != null)// {// ObjwifiTip.SetActive(false);// }//}void OnGUI(){GUIStyle style = new GUIStyle(GUI.skin.label);style.fontSize = 16;GUI.Label(new Rect(10, 10, 400, 30), $"当前WiFi: {currentSSID}", style);GUI.Label(new Rect(10, 40, 400, 30), $"目标WiFi: {targetWiFiName}", style);if (GUI.Button(new Rect(10, 70, 150, 30), "手动检测")){ManualCheck();}// 添加关闭按钮if (ObjwifiTip != null && ObjwifiTip.activeSelf){if (GUI.Button(new Rect(10, 110, 150, 30), "关闭提示")){CloseTipPage();}}}
}
2.Unity AndroidManifest.xml文件
①改个设置
然后会引擎会自动生成一个xml文件
Assets\Plugins\Android\AndroidManifest.xml
②补充权限语句
完整文件↓
<?xml version="1.0" encoding="utf-8"?>
<!-- GENERATED BY UNITY. REMOVE THIS COMMENT TO PREVENT OVERWRITING WHEN EXPORTING AGAIN-->
<manifestxmlns:android="http://schemas.android.com/apk/res/android"package="com.unity3d.player"xmlns:tools="http://schemas.android.com/tools"><!-- 必需的核心权限 --><uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <application><activity android:name="com.unity3d.player.UnityPlayerActivity"android:theme="@style/UnityThemeSelector"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter><meta-data android:name="unityplayer.UnityActivity" android:value="true" /></activity></application>
</manifest>
发布后在Android端运行即可看到应用系统权限请求弹窗,这时就可以对网络状态进行判断了
备注:
测试发现存在一个问题()。
原因分析
Android系统延迟:Android的WiFi状态更新不是实时的,系统需要时间检测到网络断开
连接信息缓存:WifiInfo 对象中的信息不是实时更新的,会有短暂延迟
心跳检测机制:你的检测间隔是1秒,加上系统延迟,总共可能需要6-9秒
测试问题 | 分析 |
---|---|
当离开指定WiFi区域时,系统的WiFi图标已经消失后6~9s之后,软件的检测才显示WiFi丢失 | Android系统延迟-Android的WiFi状态更新不是实时的,系统需要时间检测到网络断开,连接信息缓存-WifiInfo 对象中的信息不是实时更新的,会有短暂延迟,心跳检测机制-你的检测间隔是1秒,加上系统延迟,总共可能需要6-9秒 |