您的位置:首页 > 移动开发

例子:Bluetooth app to device sample

2013-08-14 17:54 381 查看
本例子演示了:

判断蓝牙是否打开,是通过一个HRsult值为0x8007048F的异常来判断的

catch (Exception ex)
{
if ((uint)ex.HResult == 0x8007048F)
{
var result = MessageBox.Show(AppResources.Msg_BluetoothOff, "Bluetooth Off", MessageBoxButton.OKCancel);
if (result == MessageBoxResult.OK)
{
ShowBluetoothcControlPanel();
}
}


找到所有配对设备 - Windows.Networking.Proximity.PeerFinder

PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";
var peers = await PeerFinder.FindAllPeersAsync();


尝试连接已配对设备

//从数据中获取已经选中的蓝牙设备,在ConnectToDevice方法中连接

PairedDeviceInfo pdi = PairedDevicesList.SelectedItem as PairedDeviceInfo;
PeerInformation peer = pdi.PeerInfo;

// Asynchronous call to connect to the device
ConnectToDevice(peer);


ConnectToDevice:

Windows.Networking.Sockets;

try
{
Windows.Networking.Sockets.StreamSocket _socket = new StreamSocket();
string serviceName = (String.IsNullOrWhiteSpace(peer.ServiceName)) ? tbServiceName.Text : peer.ServiceName;

// Note: If either parameter is null or empty, the call will throw an exception
await _socket.ConnectAsync(peer.HostName, serviceName);

// If the connection was successful, the RemoteAddress field will be populated
MessageBox.Show(String.Format(AppResources.Msg_ConnectedTo, _socket.Information.RemoteAddress.DisplayName));
}


当捕获蓝牙未打开的异常,后打开蓝牙设置页面:(Microsoft.Phone.Tasks)

private void ShowBluetoothcControlPanel()
{
ConnectionSettingsTask connectionSettingsTask = new ConnectionSettingsTask();
connectionSettingsTask.ConnectionSettingsType = ConnectionSettingsType.Bluetooth;
connectionSettingsTask.Show();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐