Windows phone 8 可利用的數據通信方式比較廣泛,在硬件支持的前提下,我們可以利用WiFi、藍牙、臨近感應等多種方式。數據交互一般通過套接字來完成,我們將在本文詳細的分析。
快速導航:
一、WP8套接字
二、藍牙
三、NFC
四、獲取網絡狀態
五、訪問web的幾種方式
一、WP8套接字
1)創建套接字客戶端
Windows phone 8中的套接字並不支持發布服務端,我們只能利用它在手機上創建套接字客戶端,我們在此例中要用套接字去訪問web服務器。首先,我們定義一個SocketClient來表示套接字客戶端。
public class SocketClient
{
//緩存套接字對象以便在整個生命周期重用
Socket _socket = null;
// 信號通知對象,用於異步操作完成通知
static ManualResetEvent _clientDone = new ManualResetEvent(false);
/// <summary>
/// 為每個異步調用設置超時時間
/// </summary>
const int TIMEOUT_MILLISECONDS = 30000;
/// <summary>
/// 數據緩沖區大小
/// </summary>
const int MAX_BUFFER_SIZE = 2048 * 100;
/// <summary>
/// 關閉套接字連接和釋放所有相關的資源
/// </summary>
public void Close()
{
if (_socket != null)
{
_socket.Close();
}
}
}
連接:
[C#]
/// <summary>
/// 嘗試用TCP套接字連接到指定主機端口
/// </summary>
/// <param name="hostName">主機名</param>
/// <param name="portNumber">端口號</param>
/// <returns>描述連接結果</returns>
public string Connect(string hostName, int portNumber)
{
string result = string.Empty;
//創建一個終結點,主機名、端口號
DnsEndPoint hostEntry = new DnsEndPoint(hostName, portNumber);
//創建一個基於流,TCP套接字。
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//套接字上下文
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
socketEventArg.RemoteEndPoint = hostEntry;
socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
{
//執行的狀態信息
result = e.SocketError.ToString();
//將當前線程設置為收到信息狀態,這樣被阻止的線程可以繼續執行
_clientDone.Set();
});
//標識當前進程為未收到信息狀態
_clientDone.Reset();
// 發送一個異步連接請求
_socket.ConnectAsync(socketEventArg);
//將當前線程阻止,直到當前線程收到信息或者超時時間已到
_clientDone.WaitOne(TIMEOUT_MILLISECONDS);
return result;
}
[C#]
/// <summary>
/// 向連接的服務器發送信息
/// </summary>
/// <param name="data">數據正文</param>
/// <returns>反饋</returns>
public string Send(string data)
{
string response = "操作超時";
//套接字是否准備好
if (_socket != null)
{
//套接字上下文
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
socketEventArg.RemoteEndPoint = _socket.RemoteEndPoint;
socketEventArg.UserToken = null;
socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
{
response = e.SocketError.ToString();
_clientDone.Set();
});
byte[] payload = Encoding.UTF8.GetBytes(data);
socketEventArg.SetBuffer(payload, 0, payload.Length);
_clientDone.Reset();
_socket.SendAsync(socketEventArg);
_clientDone.WaitOne(TIMEOUT_MILLISECONDS);
}
else
{
response = "套接字沒有准備好";
}
return response;
}
接受消息:
[C#]
/// <summary>
/// 從連接服務器接收數據
/// </summary>
/// <returns>The data received from the server</returns>
public string Receive()
{
string response = "操作超時";
if (_socket != null)
{
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
socketEventArg.RemoteEndPoint = _socket.RemoteEndPoint;
//設置接收數據的緩沖區
socketEventArg.SetBuffer(new Byte[MAX_BUFFER_SIZE], 0, MAX_BUFFER_SIZE);
socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
{
if (e.SocketError == SocketError.Success)
{
// Retrieve the data from the buffer
response = Encoding.UTF8.GetString(e.Buffer, e.Offset, e.BytesTransferred);
response = response.Trim('\0');
}
else
{
response = "錯誤:" + e.SocketError.ToString();
}
_clientDone.Set();
});
_clientDone.Reset();
_socket.ReceiveAsync(socketEventArg);
_clientDone.WaitOne(TIMEOUT_MILLISECONDS);
}
else
{
response = "套接字沒有准備好";
}
return response;
}
2)通過套接字訪問HTTP網站
現在我們有了套接字客戶端,這個時候我們來做一個類似於瀏覽器的功能,我們模擬HTTP請求發送到web服務器,代碼如下:
<!--LayoutRoot 是包含所有頁面內容的根網格-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--TitlePanel 包含應用程序的名稱和頁標題-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="套接字訪問web" Style="{StaticResource PhoneTextNormalStyle}"/>
</StackPanel>
<!--ContentPanel - 在此處放置其他內容-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<TextBox x:Name="textbox1" HorizontalAlignment="Left" Height="72" Margin="-10,-17,0,0" TextWrapping="Wrap" Text="www.hao123.com" VerticalAlignment="Top" Width="395"/>
<Button Content="轉到" HorizontalAlignment="Left" Margin="364,-17,-9,0" VerticalAlignment="Top" Click="Button_Click_1"/>
</Grid>
<ScrollViewer Height="649" Width="468" Margin="12,47,0,0" HorizontalAlignment="Left" Grid.Row="1" VerticalAlignment="Top" >
<TextBlock ScrollViewer.HorizontalScrollBarVisibility="Visible" ScrollViewer.VerticalScrollBarVisibility="Visible" x:Name="textblok1" Height="649" Width="468" MaxHeight="649" MaxWidth="468" />
</ScrollViewer>
</Grid>
[C#]
private void Button_Click_1(object sender, RoutedEventArgs e)
{
string hostName = textbox1.Text.Replace("http://", string.Empty);
SocketClient client = new SocketClient();
//主機,端口號
textblok1.Text = client.Connect(hostName, 80);
//模擬一個HTTP Get請求
textblok1.Text = client.Send("GET http://" + hostName + " HTTP/1.0\r\nHost: " + hostName + "\r\n\r\n\r\n");
//等待相應
textblok1.Text = client.Receive();
}
二、藍牙
WP8藍牙支持對等方應用連接,也支持其他藍牙設備,下面我們看看如何連接到對等方應用和設備。
1)連接到對等方
[C#] //已經搜索到的對等方列表
IReadOnlyList<PeerInformation> peers;
// 開始連接到對等應用
async void AppToApp()
{
// 開始查找對等項,如果有這句話,即可使自己能夠被其他藍牙設備搜索到
PeerFinder.Start();
peers = await PeerFinder.FindAllPeersAsync();
if (peers.Count == 0)
{
// 沒有發現
}
else
{
// 選擇第一個對等應用
PeerInformation selectedPeer = peers[0];
// 連接到第一個對等方應用
var streamSocket = await PeerFinder.ConnectAsync(selectedPeer);
}
}
2)連接到設備
PeerFinder.AlternateIdentities["Bluetooth:Paired"] = ""; 查找所有已配對的設備。這樣連接找到的設備對應的PeerInformation.ServiceName將為空,所以我們不能通過PeerFinder.ConnectAsync(selectedPeer);的方式去連接,具體示例如下:
[C#] //搜尋全部藍牙設備並連接第一個
private async void AppToDevice()
{
// 搜索所有配對的設備
PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";
var pairedDevices = await PeerFinder.FindAllPeersAsync();
if (pairedDevices.Count == 0)
{
//沒有發現設備
}
else
{
// 選擇第一個連接的設備,此時selectedDevice.ServiceName為空
PeerInformation selectedDevice = pairedDevices[0];
// 主動創建一個StreamSocket
StreamSocket socket = new StreamSocket();
// 第二個參數是一個RFCOMM端口號,范圍是1-30
await socket.ConnectAsync(selectedDevice.HostName, "1");
}
}
PeerFinder.AlternateIdentities["Bluetooth:SDP"] = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX";查找使用服務發現協議 (SDP) 並通過既定 GUID 播發服務的設備
[C#] //搜尋特定GUID的設備
private async void AppToDevice2()
{
PeerFinder.AlternateIdentities["Bluetooth:SDP"] = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX";
var pairedDevices = await PeerFinder.FindAllPeersAsync();
if (pairedDevices.Count == 0)
{
//沒有發現設備
}
else
{
// 選擇第一個連接的設備
PeerInformation selectedDevice = pairedDevices[0];
// 主動創建一個StreamSocket
StreamSocket socket = new StreamSocket();
// 這種情況下selectedDevice.ServiceName等於您指定的GUID
await socket.ConnectAsync(selectedDevice.HostName, selectedDevice.ServiceName);
}
}
3)偵聽連接請求
[C#] public Page1()
{
InitializeComponent();
//偵聽連接請求需要先添加事件
Loaded += MainPage_Loaded;
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
//遠程對等類異步連接時觸發
PeerFinder.ConnectionRequested += PeerFinder_ConnectionRequested;
}
async void PeerFinder_ConnectionRequested(object sender, ConnectionRequestedEventArgs args)
{
// 獲取到請求連接的對等方
var peer = args.PeerInformation;
// 回應連接
var streamSocket = await PeerFinder.ConnectAsync(peer);
}
4)發送消息
[C#] /// <summary>
/// 在已連接的情況下發送消息
/// </summary>
/// <param name="socket"></param>
public async void Send(StreamSocket socket, string msg)
{
var _dataWriter = new DataWriter(socket.OutputStream);
//寫入消息的長度
uint strLength = _dataWriter.MeasureString(msg);
_dataWriter.WriteUInt32(strLength);
//寫入消息的內容
_dataWriter.WriteString(msg);
uint numBytesWritten = await _dataWriter.StoreAsync();
}
5)接收消息
[C#] /// <summary>
/// 在已連接的情況下讀取消息
/// </summary>
/// <param name="socket"></param>
public async Task<string> Read(StreamSocket socket)
{
var _dataReader = new DataReader(socket.InputStream);
// 讀取消息長度
await _dataReader.LoadAsync(sizeof(uint));
uint msgLength = (uint)_dataReader.ReadUInt32();
// 讀取消息的內容
await _dataReader.LoadAsync(msgLength);
return _dataReader.ReadString(msgLength);
}
三、NFC
當兩個設備距離較近時,可以使用近場通信技術,本文演示一個使用近場通信制作聊天軟件的例子。
[XAML] <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<TextBlock x:Name="textblock1" Text="連接狀態:未連接" HorizontalAlignment="Left" Margin="10,0,0,0" TextWrapping="Wrap" VerticalAlignment="Top">
</TextBlock>
<TextBox x:Name="textbox1" HorizontalAlignment="Left" Height="72" Margin="0,27,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="386"/>
<Button Content="發送" HorizontalAlignment="Left" Margin="369,29,-9,0" VerticalAlignment="Top" Click="Button_Click_1"/>
<ListBox x:Name="listbox1" Margin="0,100,0,0" Grid.Row="1"/>
</Grid>
public partial class MainPage : PhoneApplicationPage
{
ProximityDevice device;
long typeId = -1;
long msgId = -1;
public MainPage()
{
InitializeComponent();
device = ProximityDevice.GetDefault();
if (device == null)
{
IsEnabled = false;
textblock1.Text = "您的手機不支持NFC功能";
}
else
{
//設備進入NFC識別范圍時觸發
device.DeviceArrived += device_DeviceArrived;
//設備離開NFC識別范圍時觸發
device.DeviceDeparted += device_DeviceDeparted;
}
}
//設備進入NFC識別范圍時觸發
void device_DeviceArrived(ProximityDevice sender)
{
//創建消息訂閱,創建好后就可以直接發消息了
typeId = sender.SubscribeForMessage("Windows.MyMsgType", MsgReceivedHandler);
Dispatcher.BeginInvoke(() => textblock1.Text = "連接狀態:已連接");
}
//設備離開NFC識別范圍時觸發
void device_DeviceDeparted(ProximityDevice sender)
{
if (typeId != -1)
{
//取消消息訂閱
sender.StopSubscribingForMessage(typeId);
typeId = -1;
}
Dispatcher.BeginInvoke(() => textblock1.Text = "連接狀態:連接中斷");
}
/// <summary>
/// 接收到消息后的處理邏輯
/// </summary>
void MsgReceivedHandler(ProximityDevice sender, ProximityMessage message)
{
Dispatcher.BeginInvoke(() =>
{
listbox1.Items.Add(("對方:" + message.DataAsString));
});
}
/// <summary>
/// 發送消息按鈕按下時
/// </summary>
private void Button_Click_1(object sender, RoutedEventArgs e)
{
if (textbox1.Text != string.Empty)
{
listbox1.Items.Add("我:" + textbox1.Text);
if (msgId != -1)
device.StopPublishingMessage(msgId);
msgId = device.PublishMessage("Windows.MyMsgType", textbox1.Text);
}
}
}
現在我們看看在模擬器中的效果,如下圖。模擬器中實現NFC的模擬效果請下載:http://proximitytapper.codeplex.com

四、獲取網絡狀態
很多時候,應用可能需要利用到網絡,這個時候我們需要獲取一些信息,比如網絡是否連接,當前是連接到WiFi還是運營商蜂窩網絡。這些信息關系到您的應用是否能正常工作,或者是否處於免費網絡下可執行高流量下載等操作。
1. 數據感知
數據感知功能可以用來獲取網絡成本信息以及流量計划,幫助用戶合理使用手機流量,我們看看使用方法。
[C#]var connectionProfile = Windows.Networking.Connectivity.NetworkInformation.GetInternetConnectionProfile(); //網絡接口類型 var ianaInterfaceType = connectionProfile.NetworkAdapter.IanaInterfaceType; //連接成本信息 var connectionCost = connectionProfile.GetConnectionCost(); //當前的網絡使用成本 var networkCostType = connectionCost.NetworkCostType; //計划流量是否快用完 var approachingDataLimit = connectionCost.ApproachingDataLimit; //是否超過計划流量 var overDataLimit = connectionCost.OverDataLimit; //是否漫游 var roaming = connectionCost.Roaming;
2. 網絡信息獲取
我們可以通過API獲取網絡接口狀態,檢查手機數據網絡以及WiFi連接情況等。
[XAML] <!--ContentPanel - 在此處放置其他內容-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<TextBlock x:Name="textblock1" HorizontalAlignment="Left" Margin="157,10,0,0" TextWrapping="Wrap" Text="未知" VerticalAlignment="Top"/>
<TextBlock HorizontalAlignment="Left" Margin="17,10,0,0" TextWrapping="Wrap" Text="移動運營商:" VerticalAlignment="Top"/>
<TextBlock x:Name="textblock2" HorizontalAlignment="Left" Margin="154,50,0,0" TextWrapping="Wrap" Text="未知" VerticalAlignment="Top" Height="220" Width="292"/>
<TextBlock HorizontalAlignment="Left" Margin="14,50,0,0" TextWrapping="Wrap" Text="網絡信息:" VerticalAlignment="Top"/>
<TextBlock x:Name="textblock3" HorizontalAlignment="Left" Margin="91,275,0,0" TextWrapping="Wrap" Text="未知" VerticalAlignment="Top" Height="182" Width="365"/>
<TextBlock HorizontalAlignment="Left" Margin="17,275,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Height="106" Width="69">
<Run Text="套接字連接信息:"/>
</TextBlock>
<Button Content="<-" HorizontalAlignment="Left" Margin="370,617,0,0" VerticalAlignment="Top" Width="86" Click="Button_Click_1"/>
</Grid>
Socket socket;
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
//移動運營商
textblock1.Text = DeviceNetworkInformation.CellularMobileOperator;
//網絡信息
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("網絡是否可用: ");
sb.AppendLine(DeviceNetworkInformation.IsNetworkAvailable.ToString());
sb.Append("是否啟用蜂窩數據: ");
sb.AppendLine(DeviceNetworkInformation.IsCellularDataEnabled.ToString());
sb.Append("是否允許漫游: ");
sb.AppendLine(DeviceNetworkInformation.IsCellularDataRoamingEnabled.ToString());
sb.Append("是否啟用Wi-Fi: ");
sb.AppendLine(DeviceNetworkInformation.IsWiFiEnabled.ToString());
//網絡接口信息
sb.Append("網絡接口類型: ");
var networkInterfaceType = NetworkInterface.NetworkInterfaceType;
var networkInterfaceTypeString = networkInterfaceType.ToString() + "(" + InterfaceTypeConvert.Convert(networkInterfaceType) + ")";
sb.AppendLine(networkInterfaceTypeString);
sb.Append("網絡接口子類型: ");
var networkSubInterfaceTypeString = string.Empty;
DeviceNetworkInformation.ResolveHostNameAsync(new DnsEndPoint("www.baidu.com", 80),
new NameResolutionCallback(x =>
{
networkSubInterfaceTypeString = x.NetworkInterface.InterfaceSubtype.ToString() + "[" + InterfaceTypeConvert.ConvertSub(x.NetworkInterface.InterfaceSubtype) + "]";
sb.AppendLine(networkSubInterfaceTypeString);
Dispatcher.BeginInvoke(() => { textblock2.Text = sb.ToString(); });
}), null);
//套接字連接信息
DnsEndPoint hostEntry = new DnsEndPoint("www.baidu.com", 80);
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//設置連接要求,必須為使用蜂窩技術網絡
socket.SetNetworkRequirement(NetworkSelectionCharacteristics.Cellular);
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
socketEventArg.RemoteEndPoint = hostEntry;
socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e1)
{
NetworkInterfaceInfo netInterfaceInfo = socket.GetCurrentNetworkInterface();
StringBuilder sb2 = new StringBuilder();
sb2.AppendLine("最后更新: " + DateTime.Now.ToString());
sb2.Append("網絡接口名: ");
sb2.AppendLine(netInterfaceInfo.InterfaceName);
sb2.Append("網絡接口狀態: ");
sb2.AppendLine(netInterfaceInfo.InterfaceState.ToString());
sb2.Append("網絡接口類型: ");
sb2.AppendLine(netInterfaceInfo.InterfaceType.ToString());
sb2.Append("網絡接口子類型: ");
sb2.AppendLine(netInterfaceInfo.InterfaceSubtype.ToString());
Dispatcher.BeginInvoke(() => textblock3.Text = sb2.ToString());
});
socket.ConnectAsync(socketEventArg);
base.OnNavigatedTo(e);
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri("/Page1.xaml", UriKind.Relative));
}
3. 檢測網絡狀態改變
手機的網絡連接並不如電腦穩定,當你到信號不好的地方,或者自動連接上WiFi等情況,怎么通過代碼自動監測呢,下面演示了當手機網絡改變時,列舉出日志清單,並實時刷新網絡信息。
[XAML] <!--LayoutRoot 是包含所有頁面內容的根網格-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="網絡狀態改變測試" Style="{StaticResource PhoneTextNormalStyle}"/>
</StackPanel>
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Text="可用的網絡接口" FontSize="{StaticResource PhoneFontSizeLarge}"/>
<ListBox Grid.Row="1" x:Name="lbNetworkInterfaces" ItemsSource="{Binding}" Background="LightGray" >
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" Margin="5,5,0,5" Foreground="Black"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<TextBlock Grid.Row="2" Text="事件日志" FontSize="{StaticResource PhoneFontSizeLarge}"/>
<ScrollViewer Grid.Row="3" Background="LightGray" BorderThickness="1">
<ListBox x:Name="lbNetworkChanges" ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" Foreground="Black"
FontSize="{StaticResource PhoneFontSizeNormal}" TextWrapping="Wrap" Margin="5,10,0,10" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</ScrollViewer>
<TextBlock Grid.Row="4" Text="網絡狀態" FontSize="{StaticResource PhoneFontSizeLarge}"/>
<Grid Grid.Row="5" Background="LightGray" >
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Text="網絡是否可用" Foreground="Black" Margin="5,5,0,5" />
<TextBlock Grid.Row="0" Grid.Column="1" x:Name="tbIsNetworkAvailable" HorizontalAlignment="Center" Foreground="Black" />
<TextBlock Grid.Row="1" Grid.Column="0" Foreground="Black" Margin="5,5,0,5" >
<Run Text="WiFi是否可用"/>
</TextBlock>
<TextBlock Grid.Row="1" Grid.Column="1" x:Name="tbIsWiFiEnabled" HorizontalAlignment="Center" Foreground="Black"/>
<TextBlock Grid.Row="2" Grid.Column="0" Text="是否啟用蜂窩數據" Foreground="Black" Margin="5,5,0,5" />
<TextBlock Grid.Row="2" Grid.Column="1" x:Name="tbIsCellularDataEnabled" HorizontalAlignment="Center" Foreground="Black"/>
</Grid>
<Button Grid.Row="6" x:Name="btnChangeNetworkSettings" Content="飛行" Click="Button_Click_3" Margin="314,0,46,0"/>
<Button Content="->" Margin="391,0,-15,0" Grid.Row="6" Click="Button_Click_1"/>
<Button Content="刷新" Margin="-15,0,370,0" Grid.Row="6" Click="Button_Click_2"/>
<Button Content="WiFi" Margin="66,0,288,0" Grid.Row="6" Click="Button_Click_3" />
<Button Content="網絡" Margin="150,0,204,0" Grid.Row="6" Click="Button_Click_3" />
<Button Content="藍牙" Margin="232,0,122,0" Grid.Row="6" Click="Button_Click_3" />
</Grid>
</Grid>
public partial class Page1 : PhoneApplicationPage
{
public ObservableCollection<string> Changes { get; set; }
public ObservableCollection<string> NetworkInterfaces { get; set; }
public Page1()
{
InitializeComponent();
// 網絡可用性改變事件日志
Changes = new ObservableCollection<string>();
lbNetworkChanges.DataContext = Changes;
//當前可用的網絡接口
NetworkInterfaces = new ObservableCollection<string>();
lbNetworkInterfaces.DataContext = NetworkInterfaces;
//網絡可用性改變時
DeviceNetworkInformation.NetworkAvailabilityChanged += new EventHandler<NetworkNotificationEventArgs>(ChangeDetected);
UpdateNetworkInterfaces();
UpdateNetworkStatus();
}
void ChangeDetected(object sender, NetworkNotificationEventArgs e)
{
string change = string.Empty;
switch (e.NotificationType)
{
case NetworkNotificationType.InterfaceConnected:
change = "連接: ";
break;
case NetworkNotificationType.InterfaceDisconnected:
change = "斷開: ";
break;
case NetworkNotificationType.CharacteristicUpdate:
change = "變更: ";
break;
default:
change = "未知: ";
break;
}
string changeInformation = String.Format(" {0} {1} {2} ({3})",
DateTime.Now.ToShortTimeString(), change, e.NetworkInterface.InterfaceName,
InterfaceTypeConvert.Convert(e.NetworkInterface.InterfaceType) + "," + InterfaceTypeConvert.ConvertSub(e.NetworkInterface.InterfaceSubtype));
Dispatcher.BeginInvoke(() =>
{
Changes.Add(changeInformation);
UpdateNetworkStatus();
UpdateNetworkInterfaces();
});
}
//更新網絡接口
private void UpdateNetworkInterfaces()
{
NetworkInterfaces.Clear();
//獲取網絡接口列表
NetworkInterfaceList networkInterfaceList = new NetworkInterfaceList();
foreach (NetworkInterfaceInfo networkInterfaceInfo in networkInterfaceList)
{
NetworkInterfaces.Add(String.Format("{0} ({1},{2})",
networkInterfaceInfo.InterfaceName,
InterfaceTypeConvert.Convert(networkInterfaceInfo.InterfaceType),
InterfaceTypeConvert.ConvertSub(networkInterfaceInfo.InterfaceSubtype)));
}
}
//更新網絡狀態
private void UpdateNetworkStatus()
{
tbIsCellularDataEnabled.Text = (DeviceNetworkInformation.IsCellularDataEnabled) ? "是" : "否";
tbIsNetworkAvailable.Text = (DeviceNetworkInformation.IsNetworkAvailable) ? "是" : "否";
tbIsWiFiEnabled.Text = (DeviceNetworkInformation.IsWiFiEnabled) ? "是" : "否";
}
//連接設置
private void Button_Click_3(object sender, RoutedEventArgs e)
{
var settringTypeString = string.Empty;
var button = sender as Button;
if (button != null) settringTypeString = Convert.ToString(button.Content);
var settringType = ConnectionSettingsType.WiFi;
switch (settringTypeString)
{
case "飛行": settringType = ConnectionSettingsType.AirplaneMode;
break;
case "網絡": settringType = ConnectionSettingsType.Cellular;
break;
case "藍牙": settringType = ConnectionSettingsType.Bluetooth;
break;
default: break;
}
//連接設置選擇框
ConnectionSettingsTask connectionSettings = new ConnectionSettingsTask();
// 連接設置的類型
connectionSettings.ConnectionSettingsType = settringType;
connectionSettings.Show();
}
//刷新
private void Button_Click_2(object sender, RoutedEventArgs e)
{
UpdateNetworkStatus();
UpdateNetworkInterfaces();
Changes.Clear();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
}
}
五、訪問web的幾種方式
Windows phone中訪問Internet的方式主要有:通過套接字、WebClient 類、HttpWebRequest 類、服務引用等。套接字我們已經講過。我主要講解后面三種。
WebClient 類:一般用於通過訪問URL獲取特定的資源,下面是使用方法:
[C#]WebClient webClient = new WebClient();
webClient.DownloadStringAsync(new Uri("http://www.baidu.com", UriKind.Absolute));
webClient.DownloadStringCompleted += (a, b) =>
{
if (b.Error == null && !b.Cancelled)
{
Dispatcher.BeginInvoke(() => MessageBox.Show(b.Result));
}
};
HttpWebRequest 類:對http做了基本的實現,相當於比直接用socket方便一點。
[C#] Uri uri = new Uri("http://192.168.100.212");
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
httpWebRequest.Method = "POST";
//異步獲取HTTP請求正文流
httpWebRequest.BeginGetRequestStream(new AsyncCallback(a =>
{
var httpWebRequest2 = a.AsyncState as HttpWebRequest;
var stream = httpWebRequest2.EndGetRequestStream(a);
var streamWriter = new StreamWriter(stream);
//在HTTP請求正文流中寫入要POST的參數
streamWriter.WriteLine("wd=111");
streamWriter.Close();
//開始異步的向遠程主機發送HTTP請求
httpWebRequest2.BeginGetResponse(new AsyncCallback(b =>
{
try
{
var httpWebRequest3 = b.AsyncState as HttpWebRequest;
//請求執行完成,得到HTTP相應
WebResponse webResponse = httpWebRequest3.EndGetResponse(b);
var s = webResponse.ContentType;
//獲取到HTTP相應正文流
var stream3 = webResponse.GetResponseStream();
//讀出來,轉換成字符串
var streamReader = new StreamReader(stream3, Encoding.UTF8);
var text = streamReader.ReadToEnd();
Dispatcher.BeginInvoke(() => MessageBox.Show(text));
}
catch (Exception ex)
{
var c = ex.Message;
}
}), httpWebRequest2);
}), httpWebRequest);
服務引用:其實於一般的服務引用一樣,只不過這里只支持異步實現。
[C#]//添加服務引用后,下面代碼為異步調用web服務
ServiceReference1.WebService1SoapClient c = new ServiceReference1.WebService1SoapClient();
c.HelloWorldAsync("");
c.HelloWorldCompleted += (a, b) =>
{
Dispatcher.BeginInvoke(() => MessageBox.Show(b.Result));
};
出處:[ http://www.cnblogs.com/lipan/]
版權聲明:本文的版權歸作者與博客園共有。轉載時須注明原文出處以及作者,並保留原文指向型鏈接,不得更改原文內容。否則作者將保留追究其法律責任。
