在Windows Phone 開發中有時候需要擷取裝置當前串連網路的類型,是Wifi,還是2G,3G,或者4G,SDK中提供擷取網路類型的API(Microsoft.Phone.Net.NetworkInformation. DeviceNetworkInformation),通過此API我們可以方便的擷取相關資訊。但是此API是基於非同步回調的方式擷取的,如果需要同步擷取,那麼就需要做一些特殊的處理。
以下代碼定義網路類型資訊類,用於儲存擷取的網路類型資訊。
/// <summary> /// 網路類型 /// </summary> public enum NetworkType { None = 0, Wifi = 1, //Wifi Mobile2G = 2, //2G網路 Mobile3G = 3, //3G網路 Mobile4G = 4 //4G網路 } /// <summary> /// 網路類型資訊 /// </summary> public class NetworkInfo { /// <summary> /// 網路介面的名稱 /// </summary> public string InterfaceName { get; set; } /// <summary> /// 網路介面的說明 /// </summary> public string Description { get; set; } /// <summary> /// 網路類型 /// </summary> public NetworkType InterfaceType { get; set; } }
以下代碼將從系統NetworkInterfaceInfo解析擷取網路類型資訊並寫入到上面構造的NetworkInfo類中。
private static NetworkInfo parseNetworkInfo(NetworkInterfaceInfo info) { NetworkInfo netInfo = new NetworkInfo(); if (info != null) { netInfo.InterfaceName = info.InterfaceName; netInfo.Description = info.Description; switch (info.InterfaceType) { case NetworkInterfaceType.MobileBroadbandCdma: case NetworkInterfaceType.MobileBroadbandGsm: switch (info.InterfaceSubtype) { case NetworkInterfaceSubType.Cellular_GPRS: case NetworkInterfaceSubType.Cellular_1XRTT: case NetworkInterfaceSubType.Cellular_EDGE: netInfo.InterfaceType = NetworkType.Mobile2G; break; case NetworkInterfaceSubType.Cellular_3G: case NetworkInterfaceSubType.Cellular_EVDO: case NetworkInterfaceSubType.Cellular_EVDV: case NetworkInterfaceSubType.Cellular_HSPA: netInfo.InterfaceType = NetworkType.Mobile3G; break; case NetworkInterfaceSubType.Cellular_LTE: case NetworkInterfaceSubType.Cellular_EHRPD: netInfo.InterfaceType = NetworkType.Mobile4G; break; default: netInfo.InterfaceType = NetworkType.None; break; } break; case NetworkInterfaceType.Wireless80211: netInfo.InterfaceType = NetworkType.Wifi; break; default: netInfo.InterfaceType = NetworkType.None; break; } } return netInfo; }
查看本欄目更多精彩內容:http://www.bianceng.cnhttp://www.bianceng.cn/OS/extra/