在uwp开发中,有时候,我们需要判断用户所在的网络,是WiFi,还是移动网络,给用户提醒,以免造成用户流量的损失,uwp中提供了用户所在网络的一些信息,但具体的类型,需要我们进一步判断处理。如下
这个静态类我已经写好了,用的时候只需调用它的 GetConnectionGeneration()方法即可返回当前网络类型。可以检测到的类型有2G、3G、4G、WiFi、LAN等。最后,为大家奉上代码。同时,欢迎热爱UWP开发的同学加入群:193148992 交流探讨。
public static class InternetStatus { static string None = "None"; static string Unknown = "Unknown"; static string IIG = "2G"; static string IIIG = "3G"; static string IVG = "4G"; static string Wifi = "wifi"; static string Lan = "Lan"; public static string GetConnectionGeneration() { bool isConnected = false; string InternetType = null; ConnectionProfile profile = NetworkInformation.GetInternetConnectionProfile(); if (profile == null) { InternetType = InternetStatus.None; } else { NetworkConnectivityLevel cl = profile.GetNetworkConnectivityLevel(); isConnected = (cl != NetworkConnectivityLevel.None); } if (!isConnected) { return InternetStatus.None; } if (profile.IsWwanConnectionProfile) { if (profile.WwanConnectionProfileDetails == null) { InternetType = InternetStatus.Unknown; } WwanDataClass connectionClass = profile.WwanConnectionProfileDetails.GetCurrentDataClass(); switch (connectionClass) { //2G case WwanDataClass.Edge: case WwanDataClass.Gprs: InternetType = InternetStatus.IIG; break; //3G case WwanDataClass.Cdma1xEvdo: case WwanDataClass.Cdma1xEvdoRevA: case WwanDataClass.Cdma1xEvdoRevB: case WwanDataClass.Cdma1xEvdv: case WwanDataClass.Cdma1xRtt: case WwanDataClass.Cdma3xRtt: case WwanDataClass.CdmaUmb: case WwanDataClass.Umts: case WwanDataClass.Hsdpa: case WwanDataClass.Hsupa: InternetType = InternetStatus.IIIG; break; //4G case WwanDataClass.LteAdvanced: InternetType = InternetStatus.IVG; break; //无网 case WwanDataClass.None: InternetType = InternetStatus.Unknown; break; case WwanDataClass.Custom: default: InternetType = InternetStatus.Unknown; break; } } else if (profile.IsWlanConnectionProfile) { InternetType = InternetStatus.Wifi; } else { ///不是Wifi也不是蜂窝数据判断为Lan InternetType = InternetStatus.Lan; } return InternetType; } }
时间: 2024-10-09 19:49:39