using ShadowStudio.UI; using System; using System.Collections; using System.Collections.Generic; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Runtime.CompilerServices; using UnityEngine; using UnityEngine.Events; using XRTool.Util; namespace LGS.Common_20200526 { public class NetStatus : MonoBehaviour { private static NetStatus mInstant; public static NetStatus Instant { get { return mInstant; } } string m_ReachabilityText = ""; string netStatus=""; bool isOne = false; private event Action NetWorkChangeCallBack; private NetworkReachability preNetWorkStatus = NetworkReachability.NotReachable; private void Awake() { if (mInstant != null) { DestroyImmediate(gameObject); return; } mInstant = this; DontDestroyOnLoad(gameObject); } private void Start() { //jo = new AndroidJavaObject("com.lgs.unitylibrary2.currentNetSpeed"); //preNetWorkStatus = Application.internetReachability; //jo.Call("NetStart"); SCGetNetStatus(); StartCoroutine(GetNetSpeedAndstatus()); } void Update() { if (isOne == false) { preNetWorkStatus = Application.internetReachability; // Debug.Log(GetType().ToString() + "赋值:" + preNetWorkStatus); isOne = true; } if (preNetWorkStatus != Application.internetReachability) { if (NetWorkChangeCallBack != null) { NetWorkChangeCallBack(preNetWorkStatus, Application.internetReachability); } preNetWorkStatus = Application.internetReachability; } } private void OnDestroy() { StopCoroutine(GetNetSpeedAndstatus()); m_ReachabilityText = null; } /// /// 注册网络状态变化时触发事件,第一个参数为变化前的网络状态 /// 第二个参数为变化后的网络状态 /// /// public void RegisterNetWorkChangeCallBack(Action callback) { NetWorkChangeCallBack += callback; } public string SCGetNetStatus()//获取网络状态 { //Check if the device cannot reach the internet if (Application.internetReachability == NetworkReachability.NotReachable)//网络无法连接 { //Change the Text m_ReachabilityText = "NoNetWork"; } //Check if the device can reach the internet via a carrier data network else if (Application.internetReachability == NetworkReachability.ReachableViaCarrierDataNetwork)//网络可通过由运营商数据网络访问 { m_ReachabilityText = "3G/4GNetWork"; } //Check if the device can reach the internet via a LAN else if (Application.internetReachability == NetworkReachability.ReachableViaLocalAreaNetwork)//网络可通过WIFI或电缆访问 { m_ReachabilityText = "WifiOrCableNetWork"; } return m_ReachabilityText; } bool isPop; private IEnumerator GetNetSpeedAndstatus()//每经过1秒执行一次 { while (true) { yield return new WaitForSecondsRealtime(1f); string status = SCGetNetStatus(); switch (status) { case "NoNetWork": if(!isPop) { CommonMethod.ShowNetworkAnomalyPop(() => { isPop = false; }).GetComponent().OnClose(()=> { isPop = false; }); } isPop = true; break; case "WifiOrCableNetWork": break; } } } } }