Unity 檢測網絡-判斷當前(Android/Windows平臺)設備是否連接了指定WiFi

判斷設備是否連接了特定的網絡

    • 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秒

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/98045.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/98045.shtml
英文地址,請注明出處:http://en.pswp.cn/web/98045.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

通過網絡強化增強混合IT環境的安全

網絡是企業運營的支柱&#xff0c;也是網絡犯罪分子和惡意威脅者的主要目標&#xff0c;他們會破壞IT運營的連續性。隨著混合云基礎設施、遠程辦公和物聯網&#xff08;IoT&#xff09;生態系統的出現&#xff0c;網絡邊界正在不斷擴大&#xff0c;新的漏洞不斷產生&#xff0c…

ACP(四):RAG工作流程及如何創建一個RAG應用

RAG的工作原理 你在考試的時候有可能會因為忘記某個概念或公式而失去分數&#xff0c;但考試如果是開卷形式&#xff0c;那么你只需要找到與考題最相關的知識點&#xff0c;并加上你的理解就可以進行回答了。 對于大模型來說也是如此&#xff0c;在訓練過程中由于沒有見過某個知…

宇視設備視頻平臺EasyCVR視頻設備軌跡回放平臺監控攝像頭故障根因剖析

監控攝像頭的類型繁多&#xff0c;市場上提供了廣泛的選擇。然而&#xff0c;在使用監控攝像頭的過程中&#xff0c;用戶可能會遇到云臺在很短的時間內出現運轉不靈或完全無法轉動的問題。這里&#xff0c;我們將對這一常見問題進行深入分析。一、具體的原因&#xff1a; 1、距…

【Uni-App+SSM 寵物項目實戰】Day15:購物車添加

大家好!今天是學習路線的第15天,我們正式進入訂單與購物車核心模塊。昨天完成了商家服務列表的分頁加載,今天聚焦“購物車添加”功能——這是連接“商品瀏覽”與“訂單提交”的關鍵環節,用戶可將寵物用品(如糧食、玩具)加入購物車,后續統一結算。 為什么學這個? 購物車…

Java 黑馬程序員學習筆記(進階篇6)

常用的 API1. 正則表達式(1) 題目&#xff1a;貪婪爬取和非貪婪爬取① 貪婪爬取&#xff1a;爬取數據的時候盡可能的多獲取數據 ② 非貪婪爬取&#xff1a;爬取數據的時候盡可能的少獲取數據 ③ Java中默認的是貪婪爬取 ④ 后面加上 ? 可以轉變為非貪婪爬取(2) 捕獲分組捕獲分…

計算機網絡---數據鏈路層上

文章目錄1. 數據鏈路層的功能2. 組幀2.1 字符填充法2.2 字節填充法2.3 零比特填充法2.4 違規編碼2.5 總結3. 差錯控制3.1 檢錯編碼3.1.1 奇偶校驗3.1.2 循環冗余校驗碼&#xff08;CRC&#xff09;3.1.3 總結3.2 糾錯編碼&#xff08;海明校驗碼&#xff09;3.3 總結4. 流量控制…

機器學習實戰項目中,回歸與分類模型中該如何科學定義目標變量Y?

前言 在機器學習項目里&#xff0c;目標變量 (Y) 的定義決定了你能解答什么問題&#xff0c;以及模型能給業務帶來什么價值。選擇不當不僅可能導致模型誤差大、偏差嚴重&#xff0c;還可能讓業務決策方向偏離。 本文分兩大場景&#xff1a; 供應鏈項目中的 銷量預測&#xff08…

【 C/C++ 算法】入門動態規劃-----一維動態規劃基礎(以練代學式)

每日激勵&#xff1a;“不設限和自我肯定的心態&#xff1a;I can do all things。 — Stephen Curry” 緒論?&#xff1a; 本章是動態規劃算法的基礎入門篇&#xff0c;我將通過三道簡單題 一道中等難度的一維動態規劃題來帶你對動態規劃有個初認識&#xff0c;并基本了解動…

深入對比Tomcat與Netty:HTTP請求從網卡到Controller的全鏈路追蹤

我們日常用Spring Boot寫的RestController&#xff0c;感覺上就是一個簡單的方法&#xff0c;但它背后其實有一套復雜的網絡服務在支撐。一個HTTP請求到底是怎么從用戶的瀏覽器&#xff0c;穿過層層網絡&#xff0c;最終抵達我們代碼里的Controller方法的&#xff1f;理解這個過…

GO學習記錄十——發包

記錄下不同平臺的發包操作和期間遇到的問題 1.命令&#xff1a; $env:GOOSlinux $env:GOARCHamd64 go build -o release/HTTPServices-linux第一行&#xff0c;配置平臺&#xff0c;linux、windows 第二行&#xff0c;配置部署服務器的處理器架構 第三行&#xff0c;輸出目標文…

貪心算法與動態規劃

1. 什么是貪心算法&#xff1f; 貪心算法是一種在每一步選擇中都采取在當前狀態下最好或最優&#xff08;即最有利&#xff09;的選擇&#xff0c;從而希望導致結果是全局最好或最優的算法。 核心思想&#xff1a;“每步都貪心地選擇眼前最好的&#xff0c;不去考慮整個未來的長…

學會“讀網頁”:生成式 AI 在足球賽事信息整理中的實戰

逐步教程&#xff08;Step-by-Step&#xff09; — 適合初學者與教學類文章 背景&#xff08;為什么要這樣做&#xff09; 對于足球迷、資訊編輯與數據分析師來說&#xff0c;最快、最準確把握一場比賽的核心信息至關重要&#xff1a;比分、關鍵事件&#xff08;進球、點球、紅…

BM3D 圖像降噪快速算法的 MATLAB 實現

BM3D 圖像降噪快速算法的 MATLAB 實現1. 快速 BM3D 算法流程&#xff08;概述&#xff09;步驟操作加速技巧① 分組塊匹配 堆疊FFT 互相關② 協同濾波3D 變換 硬閾值FFT 沿第三維③ 聚合加權平均稀疏矩陣累加 2. 核心函數&#xff08;單文件版&#xff09; 保存為 bm3d_fast.…

Go的schedt調度(runtime/proc.go)

1. 創建go的入口函數// Create a new g running fn. // Put it on the queue of gs waiting to run. // The compiler turns a go statement into a call to this. func newproc(fn *funcval) {gp : getg()pc : sys.GetCallerPC()systemstack(func() {newg : newproc1(fn, gp, …

Ubuntu 服務器配置轉發網絡訪問

配置文檔&#xff1a;Ubuntu 服務器轉發網絡訪問 一、網絡拓撲以以下網絡拓撲為示例Ubuntu 服務器&#xff08;兩個網卡&#xff09; eth1 10.66.71.222 &#xff08;接入內網&#xff09;eno1 192.168.2.100 &#xff08;直連相機&#xff09; 相機ip 192.168.2.1 Windows 客…

為什么企業需要高防IP

1. 抵御日益猖獗的DDoS攻擊 現代DDoS攻擊規模已突破Tbps級別 傳統防火墻無法應對大規模流量攻擊 高防IP采用分布式清洗中心&#xff0c;可輕松抵御300Gbps以上的攻擊流量 2. 保障業務連續性 網絡中斷1小時可能造成數百萬損失 高防IP確保服務99.99%可用性 智能切換機制實…

CSS基礎 - 選擇器備忘錄 --筆記5

目錄基礎選擇器組合器偽類選擇器屬性選擇器選擇器可以選中頁面上的特定元素并為其指定樣式。 CSS有多種選擇器。 基礎選擇器 標簽選擇器 – tagname&#xff1a;匹配目標元素的標簽名。優先級是0,0,1。如&#xff1a;p、h1、div類選擇器 – .class&#xff1a;匹配class屬性中…

自動駕駛中的傳感器技術46——Radar(7)

衛星雷達&#xff08;又稱為分布式雷達&#xff09;主要講當前雷達的雷達信號處理計算以及雷達目標相關的一些感知算法都遷移到中央域控進行&#xff0c;雷達端基本只負責數據采集&#xff0c;這樣做的影響如下&#xff1a; 雷達端成本與功耗降低&#xff1b; 雷達端采樣得到的…

【論文閱讀】Diff-Privacy: Diffusion-based Face Privacy Protection

基于擴散模型的人臉隱私保護方法——DiffPrivacy&#xff0c;解決了兩類人臉隱私任務&#xff1a;匿名化&#xff08;anonymization&#xff09;和視覺身份信息隱藏&#xff08;visual identity information hiding&#xff09;。1. 研究背景隨著人工智能和大數據技術的普及&am…

React 原理篇 - 深入理解虛擬 DOM

一、什么是虛擬 DOM&#xff1f; 在前端開發中&#xff0c;“虛擬 DOM” 是一個高頻出現的術語&#xff0c;尤其在 React 生態中被廣泛討論。但很多開發者對它的理解往往停留在 “JS 對象” 這個表層認知上。 實際上&#xff0c;虛擬 DOM 是一種編程概念—— 在這個概念里&…