現在的只能手機對網絡的依賴程度都很高,尤其是新聞、微博、音樂、視頻、VOIP通話、游戲等 事實性高的信息類應用,但是目前國內的信息費仍然高居不下,更多的用戶只有在 WIFI 的環境下才願意進行大數據量的流量從而節約流量費用。然而為了使我們的應用更加貼心、更加人性化,如何讓我們的應用為用戶省錢呢?今天為大家介紹下如何在 Windows Phone8 中獲取和監聽網絡連接狀態。
首先在Windows Phone中可以使用 Microsoft.Phone.Net.NetworkInformation.NetworkInterface.NetworkInterfaceType 來獲取應用的網絡連接狀態。
public static string GetNetStates() { var info = Microsoft.Phone.Net.NetworkInformation.NetworkInterface.NetworkInterfaceType; switch (info) { case NetworkInterfaceType.MobileBroadbandCdma: return "CDMA"; case NetworkInterfaceType.MobileBroadbandGsm: return "CSM"; case NetworkInterfaceType.Wireless80211: return "WiFi"; case NetworkInterfaceType.Ethernet: return "Ethernet"; case NetworkInterfaceType.None: return "None"; default: return "Other"; } //return null; }
通過以上代碼肯定有同學覺得不夠,因為不能看到當前的連接究竟是一個 2G 3G 甚至是4G的連接,WIFI 連接的是什麼狀態。
這時候我們可以通過 DeviceNetworkInformation.ResolveHostNameAsync 來訪問一個連接獲取更多信息。
public void GetNetName() { DeviceNetworkInformation.ResolveHostNameAsync( new DnsEndPoint("www.microsoft.com", 80), new NameResolutionCallback(handle => { NetworkInterfaceInfo info = handle.NetworkInterface; if (info != null) { Name = info.InterfaceName + " " + info.Description + " "; switch (info.InterfaceType) { case NetworkInterfaceType.Ethernet: NetName = "Ethernet"; break; case NetworkInterfaceType.MobileBroadbandCdma: case NetworkInterfaceType.MobileBroadbandGsm: switch (info.InterfaceSubtype) { case NetworkInterfaceSubType.Cellular_3G: NetName = "Cellular_3G + 3G"; break; case NetworkInterfaceSubType.Cellular_EVDO: NetName = "Cellular_EVDO + 3G"; break; case NetworkInterfaceSubType.Cellular_EVDV: NetName = "Cellular_EVDV + 3G"; break; case NetworkInterfaceSubType.Cellular_HSPA: NetName = "Cellular_HSPA + 3G"; break; case NetworkInterfaceSubType.Cellular_GPRS: NetName = "Cellular_GPRS + 2G"; break; case NetworkInterfaceSubType.Cellular_EDGE: NetName = "Cellular_EDGE + 2G"; break; case NetworkInterfaceSubType.Cellular_1XRTT: NetName = "Cellular_1XRTT + 2G"; break; default: NetName = "None"; break; } break; case NetworkInterfaceType.Wireless80211: NetName = "WiFi"; break; default: NetName = "None"; break; } } else NetName = "None"; Deployment.Current.Dispatcher.BeginInvoke(delegate() { MessageBox.Show(Name + NetName); }); //MessageBox.Show(NetName); }), null); }
相信以上信息 相信已經有很多朋友再應用中已經使用了 我在這裡給大家總結一下,其次還有一個場景就是在網絡條件發生變化的時候,比在從室內走到室外, WIFI 條件下自動切換到蜂窩網連接。
這裡在我們的模擬器中也可以模擬這個場景 VS- tools – simulation dashboard.
其次我們要在 APP 的 Launching 的事件中注冊監聽NetworkInformation.NetworkStatusChanged 事件激發這個事件的條件分別是:
// Code to execute when the application is launching (eg, from Start) // This code will not execute when the application is reactivated private void Application_Launching(object sender, LaunchingEventArgs e) { NetworkInformation.NetworkStatusChanged += (object sener) => { Deployment.Current.Dispatcher.BeginInvoke(delegate() { MessageBox.Show("NetworkStatusChanged"); }); }; }