Windows phone 7 判断网络连接
类名:DeviceNetworkInformation
CellularMobileOperator获取蜂窝移动运营商的名称。
IsCellularDataEnabled获取一个值,该值指示网络是否启用了蜂窝数据。
IsCellularDataRoamingEnabled获取一个值,该值指示网络是否允许数据漫游。
IsNetworkAvailable获取一个值,该值指示网络是否可用。
IsWiFiEnabled获取一个值,该值指示网络是否启用了 Wi-Fi。
範例程式:實作註冊監控網路狀態的變動事件與識別變動後的網路狀態。
// Constructor public MainPage() { InitializeComponent(); Initialization(false); } private void Initialization(bool pIsRegist) { //識別是否啟動行動網路 tgsIcde.IsChecked = DeviceNetworkInformation.IsCellularDataEnabled; //識別是否啟動數據漫游 tgsIcdr.IsChecked = DeviceNetworkInformation.IsCellularDataRoamingEnabled; //識別設備網路是否有網路功能 tgsIna.IsChecked = DeviceNetworkInformation.IsNetworkAvailable; //識別是否啟動WiFi tgsIwifi.IsChecked = DeviceNetworkInformation.IsWiFiEnabled; //避免測試狀態為airplane mode if (DeviceNetworkInformation.CellularMobileOperator!= null) { //識別CellularMobileOperator的類型 switch (DeviceNetworkInformation.CellularMobileOperator.ToLower()) { case "chunghwa" tblCellularOperator.Text = "中華"; break; case "taiwanmobile" tblCellularOperator.Text = "台哥大"; break; case "fetnet" tblCellularOperator.Text = "遠傳"; break; } } if (pIsRegist == false) { //註冊監控網路狀態 DeviceNetworkInformation.NetworkAvailabilityChanged += new EventHandler<NetworkNotificationEventArgs>(NetworkAvailabilityChanged); } } void NetworkAvailabilityChanged(object sender, NetworkNotificationEventArgs e) { //取得info來識別目前網路資訊 NetworkInterfaceInfo tInfo = e.NetworkInterface; //取得網路狀態通知類型 NetworkNotificationType tNotification = e.NotificationType; string tType = string.Empty; switch (tNotification) { case NetworkNotificationType.CharacteristicUpdate tType += "CharacteristicUpdate \n"; break; case NetworkNotificationType.InterfaceConnected tType += "InterfaceConnected \n"; break; case NetworkNotificationType.InterfaceDisconnected tType += "InterfaceDisconnected \n"; break; } Dispatcher.BeginInvoke(() => { tblNetworkState.Text = tType; Initialization(true); }); } private void ApplicationBarIconButton_Click(object sender, EventArgs e) { //利用ConnectionSettingsTask修改網路狀態來測試監控網路狀態事件 ConnectionSettingsTask tConnectionSettings = new ConnectionSettingsTask(); tConnectionSettings.ConnectionSettingsType = ConnectionSettingsType.AirplaneMode; tConnectionSettings.Show(); }
執行結果: