Developers can use Bluetooth-related APIs to create applications that use the Bluetooth technology of mobile phones to make close file transfers and send incoming messages, creating more interesting and convenient applications.
In Windows Phone 8, you can use Bluetooth to communicate within your application, use the Bluetooth-related APIs to connect applications to another application, and to connect applications to one device. The Bluetooth technology for Windows Phone 8 supports two Bluetooth solutions: one is the application to the application communication, the other is the application to the device communication.
1. Application to Application communication
The process of application to application communication is that the application uses Bluetooth to find the peer application that is broadcasting the Bluetooth service, and if an application is found within the scope of the application service, the application can initiate a connection request. When the two applications accept a connection, they can communicate, and the process of communication is to use the message send receive mechanism of the socket. Using Bluetooth communication technology in Windows Phone 8 for Applications to applications, you need to add id_cap_proximity functionality options to your project's Wmappmanifest.xml file, indicating support for adjacent device communications, or an exception to the program.
2. Application to Device communication
When an application is communicating to a device, the application uses Bluetooth to find the device that provides the service, and the application can initiate a connection request if a Bluetooth device is found to be connected within the range of services provided. When the application and the device accept the connection at the same time, they can communicate with each other, and the process of communication is also a message sending receiving mechanism using the socket, similar to the application's communication to the application. Using Bluetooth communication technology for applications to devices in Windows Phone 8, you need to add id_cap_proximity and id_cap_networking feature options to the project's Wmappmanifest.xml file. Indicates support for adjacent device communication capabilities and network communication capabilities, otherwise the program will appear abnormal.
Bluetooth Programming class
In Windows Phone 8, Bluetooth programming is used primarily for Peerfinder classes, peerinformation classes, Streamsocket classes, and Connectionrequestedeventargs classes, The descriptions of these classes are shown in table 19.1. Because Bluetooth is also based on TCP protocol for message delivery, so need to use the relevant programming knowledge of the socket, as well as the Streamsocket class. The Peerfinder class is a Bluetooth lookup class, and its main members are shown in table 19.2.
Table 19.1 Description of the Bluetooth programming class
Class Name Description
Peerfinder
Used to find out if a nearby device has the same application running as the current application, and you can establish a socket connection between two applications so that you can communicate. A peer-to-peer application is another instance of an application running on another device.
Peerinformation
Contains identifying information for peer-to-peer applications or devices.
Streamsocket
Support for network traffic using a TCP socket stream.
Connectionrequestedeventargs
Represents the properties of a connectionrequested event that is passed to an application
Table 19.2 members of the Peerfinder class
Member description
BOOL Allowbluetooth
Specifies whether this instance of the Peerfinder class can connect the Proximitystreamsocket object by using Bluetooth. True if this instance of Peerfinder can connect the Proximitystreamsocket object by using Bluetooth, or false. The default is true.
BOOL Allowinfrastructure
Whether to connect to Streamsocket using the TCP/IP protocol
BOOL Allowwifidirect
Specifies whether this instance of the Peerfinder class can connect the Proximitystreamsocket object by using Wi-Fi Direct. True if this instance of Peerfinder can connect the Proximitystreamsocket object by using Wi-Fi Direct, otherwise false. The default is true.
Idictionary<string, string> alternateidentities
Gets a list of alternate AppId values to match with peer-to-peer applications on other platforms. Returns a list of alternate AppId values to match with peer applications for other platforms.
String DisplayName
Gets or sets the name that identifies the computer to the remote peer class.
Peerdiscoverytypes Supporteddiscoverytypes
Gets a value that indicates which discovery options can be used with the Peerfinder class
Event Typedeventhandler<object, connectionrequestedeventargs> connectionrequested
Occurs when a remote peer uses the ConnectAsync method to request a connection.
Event Typedeventhandler<object, triggeredconnectionstatechangedeventargs> triggeredconnectionstatechanged
Occurs during a light stroke gesture for a remote peer class.
iasyncoperation< streamsocket> ConnectAsync (peerinformation peerinformation)
The connection has discovered a peer class for a call to the Findallpeersasync method. Peerinformation: A peer information object that represents the peer class to which the connection is connected. Returns the asynchronous operation that connects the remote peer class by using the provided proximity Streamsocket object.
Iasyncoperation<ireadonlylist<peerinformation>> Findallpeersasync ()
For asynchronous browsing of peer computers running the same application in wireless range. Returns asynchronous operations that browse peer classes by using Wi-Fi direct-attached technology.
void Start (String peermessage)
Delivers messages to peer applications on adjacent devices.
void Stop ()
To stop the process of finding a peer application or broadcasting a peer-class connection
Find Bluetooth devices and peers
Finding Bluetooth devices and peers in service range is the first step in Bluetooth programming, finding Bluetooth devices and peers using the Findallpeersasync method of the Peerfinder class to find them, It then returns the information Ireadonlylist<peerinformation> the lookup list of peers asynchronously, and note that when you want to find the peer application, You must invoke the Start method of the Peerfinder class before calling the Findallpeersasync method, primarily to start the broadcast service so that the other's application can find itself. Peerinformation contains three attributes: one is the name of the DisplayName that represents the peer, which is generally the name of the other's device or the actual name of the application you are looking for, and the name of the host or the IP address that the hostname represents, Another property is the port number that servicename represents the service name or TCP protocol. You can then use the peerinformation information you find to connect and communicate.
code example to find a peer application:
Async void Apptoapp ()
{
Start Lookup Service
Peerfinder.start ();
Start find
Observablecollection<peerinformation> peers = await peerfinder.findallpeersasync ();
if (peers. Count = 0)
{
No peers found
}
Else
{
To handle a lookup peer, you can use the ConnectAsync method of the Peerfinder class to connect the selected peer to communicate
}
}
Find code examples for Bluetooth devices:
Private async void Apptodevice ()
{
Set the matching Bluetooth device to find
peerfinder.alternateidentities["bluetooth:paired"] = "";
Start find
Observablecollection<peerinformation> paireddevices = await peerfinder.findallpeersasync ();
if (paireddevices.count = 0)
{
No available Bluetooth devices found
}
Else
{
Processing the found Bluetooth device, you can create a new Streamsocket object, and then use the ConnectAsync method of the Streamsocket class to connect the Bluetooth device through hostname and servicename
}
}
Bluetooth Send Message
The Bluetooth programming sends the message mechanism to use is the TCP streamsocket way, the principle and the socket consistent. After the Bluetooth connection succeeds, you can get an object of the Streamsocket class, and then we use the object's OutputStream property to initialize a DataWriter object and send the message through the DataWriter object. The OutputStream property represents the output stream of the socket, which is used to send messages to each other. Here's a look at an example of sending a message:
Async void SendMessage (String message)
{
Joins the selected peer, Selectedpeer to the Peerinformation object that is found
Streamsocket _socket= = await peerfinder.connectasync (selectedpeer);
Create DataWriter
DataWriter _datawriter = new DataWriter (_socket. OutputStream);
Write the length of the Send message first
_datawriter.writeint32 (message. Length);
await _datawriter.storeasync ();
Last write content to send message
_datawriter.writestring (message);
await _datawriter.storeasync ();
}
Bluetooth Receive Message
Bluetooth programming reception message mechanism is also used is the TCP streamsocket way, the principle of the same as the socket. After the Bluetooth connection succeeds, you can get an object of the Streamsocket class, and then we use the object's InputStream property to initialize a DataReader object and receive the message through the DataReader object. The InputStream property represents the input stream of the socket, which is used to receive messages from each other. Here's a look at an example of receiving a message:
Async task<string> GetMessage ()
{
Joins the selected peer, Selectedpeer to the Peerinformation object that is found
Streamsocket _socket= = await peerfinder.connectasync (selectedpeer);
Create DataReader
DataReader _datareader = new DataReader (_socket. InputStream);
Read the length of the message first
Await _datareader.loadasync (4);
UINT Messagelen = (UINT) _datareader.readint32 ();
Last read the contents of the message
Await _datareader.loadasync (Messagelen);
Return _datareader.readstring (Messagelen);
}
Example: Implementing Bluetooth program transmission to the program
The following is an example of how the Bluetooth program transfers to a program: by using the Bluetooth feature to find the peripheral also to use the mobile phone, set up a connection and send test messages.
Code Listing 19-1: Bluetooth program Transfer to program (source code: 19th Chapter \examples_19_1)
MainPage.xaml File Main code
<grid x:name= "Contentpanel" grid.row= "1" margin= "12,0,12,0" >
<StackPanel>
<button x:name= "Btfindbluetooth" content= "Find the appliance via Bluetooth" click= "Btfindbluetooth_click"/>
<listbox x:name= "Lbbluetoothapp" itemssource= "{Binding}" >
<listbox.itemtemplate >
<DataTemplate>
<StackPanel>
<textblock text= "{Binding DisplayName}"/>
<textblock text= "{Binding ServiceName}"/>
<button content= "Connection" horizontalalignment= "left" width= "308" "height=" click= "Btconnect_click"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</Grid>
MainPage.xaml.cs File Main code
Using System;
Using System.Windows;
Using System.Windows.Controls;
Using Microsoft.Phone.Controls;
Using Windows.Networking.Proximity;
Using Windows.Networking.Sockets;
Using Windows.Storage.Streams;
Namespace Bluetoothdemo
{
public partial class Mainpage:phoneapplicationpage
{
Private Streamsocket _socket = null; Socket Data Flow Object
Private DataWriter _datawriter; Data write to Object
Private DataReader _datareader; Data Read objects
Public MainPage ()
{
InitializeComponent ();
Loaded + + mainpage_loaded;//page Load event
}
Find Bluetooth Peer button event handling
Private async void Btfindbluetooth_click (object sender, RoutedEventArgs e)
{
Try
{
Start to find a peer
Peerfinder.start ();
Waiting for peer to find
var peers = await peerfinder.findallpeersasync ();
if (peers. Count = 0)
{
MessageBox.Show ("No equivalent Bluetooth application found");
}
Else
{
To bind a peer project to a list
Lbbluetoothapp.itemssource = peers;
}
}
catch (Exception ex)
{
if ((UINT) ex. HResult = = 0x8007048f)
{
MessageBox.Show ("Bluetooth switched off please turn on mobile phone");
}
Else
{
MessageBox.Show (ex. message);
}
}
}
Button event handling to connect Bluetooth peers
Private async void Btconnect_click (object sender, RoutedEventArgs e)
{
Button DeleteButton = sender as Button;
Peerinformation Selectedpeer = Deletebutton.datacontext as peerinformation;
Connect to a selected peer
_socket = await peerfinder.connectasync (selectedpeer);
Using an output input stream to create a data-reading object
_datareader = new DataReader (_socket. InputStream);
_datawriter = new DataWriter (_socket. OutputStream);
Start reading messages
Peerfinder_startreader ();
}
Read messages
Async void Peerfinder_startreader ()
{
Try
{
UINT Bytesread = await _datareader.loadasync (sizeof (UINT));
if (Bytesread > 0)
{
Get the size of the message content
UINT Strlength = (UINT) _datareader.readuint32 ();
Bytesread = await _datareader.loadasync (strlength);
if (Bytesread > 0)
{
String message = _datareader.readstring (strlength);
MessageBox.Show ("Get the message:" + messages);
Start the next message read
Peerfinder_startreader ();
}
Else
{
MessageBox.Show ("The other side has closed connection");
}
}
Else
{
MessageBox.Show ("The other side has closed connection");
}
}
catch (Exception e)
{
MessageBox.Show ("Read failed:" + e.message);
}
}
Page Load Event handling
void Mainpage_loaded (object sender, RoutedEventArgs e)
{
Subscription Connection Request Events
peerfinder.connectionrequested + = peerfinder_connectionrequested;
}
Connection Request Event Handling
void Peerfinder_connectionrequested (object sender, Connectionrequestedeventargs args)
{
Connect and send messages
Connecttopeer (args. Peerinformation);
}
Connect and send messages to each other
Async void Connecttopeer (Peerinformation peer)
{
_socket = await peerfinder.connectasync (peer);
_datareader = new DataReader (_socket. InputStream);
_datawriter = new DataWriter (_socket. OutputStream);
String message = "test Messages";
UINT Strlength = _datawriter.measurestring (message);
_datawriter.writeuint32 (Strlength),//length of Write message
_datawriter.writestring (message),//content of messages written
UINT numBytesWritten = await _datawriter.storeasync ();
}
}
}
The program works as shown in Figure 19.2.
Example: Implementing a Bluetooth program connection to a device
The following is an example of a Bluetooth program connecting to a device: finding a Bluetooth device and connecting to the first Bluetooth device found.
Code Listing 19-2: Bluetooth program connection to device (source code: 19th Chapter \examples_19_2)
MainPage.xaml File Main code
<grid x:name= "Contentpanel" grid.row= "1" margin= "12,0,12,0" >
<StackPanel>
<button x:name= "Btfindbluetooth" content= "connect the surrounding Bluetooth devices" click= "Btfindbluetooth_click"/>
</StackPanel>
</Grid>
MainPage.xaml.cs File Main code
Find Bluetooth Device event handling
Private async void Btfindbluetooth_click (object sender, RoutedEventArgs e)
{
Try
{
Configure the GUID of the Peerfinder Bluetooth service to search for devices
peerfinder.alternateidentities["BLUETOOTH:SDP"] = "5bec6b8f-7eba-4452-bf59-1a510745e99d";
var peers = await peerfinder.findallpeersasync ();
if (peers. Count = 0)
{
Debug.WriteLine ("No Bluetooth device Found");
}
Else
{
Connection to the first Bluetooth device found
Peerinformation selectedpeer = peers[0];
Streamsocket socket = new Streamsocket ();
Await socket. ConnectAsync (Selectedpeer.hostname, selectedpeer.servicename);
MessageBox.Show ("Connected on the HostName:" + selectedpeer.hostname + "ServiceName:" + selectedpeer.servicename);
}
}
catch (Exception ex)
{
if ((UINT) ex. HResult = = 0x8007048f)
{
MessageBox.Show ("Bluetooth is turned off");
}
}
}
The program works as shown in Figure 19.3
window Phone 8 bluetooth Detailed development case Description
WP8 Bluetooth supports Peer-to-peer application connections and other Bluetooth devices, let's look at how to connect to peer applications and devices.
1) Connect to Peer
[C # code]
List of peers that have been searched
Ireadonlylist<peerinformation> peers;
Start connecting to Peer-to-peer applications
Async void Apptoapp ()
{
Starts looking for a peer, and if so, it can be searched by other Bluetooth devices
Peerfinder.start ();
Peers = await peerfinder.findallpeersasync ();
if (peers. Count = 0)
{
Not found
}
Else
{
Select the first Peer application
Peerinformation selectedpeer = peers[0];
Connecting to the first peer application
var streamsocket = await peerfinder.connectasync (selectedpeer);
}
}
2) connect to the device
peerfinder.alternateidentities["bluetooth:paired"] = ""; Finds all the paired devices. The corresponding peerinformation.servicename for the device found in this connection will be empty, so we cannot connect through Peerfinder.connectasync (Selectedpeer), as shown in the following example:
[C # code]
Search all Bluetooth devices and connect to the first
Private async void Apptodevice ()
{
Search for all paired devices
peerfinder.alternateidentities["bluetooth:paired"] = "";
var paireddevices = await peerfinder.findallpeersasync ();
if (paireddevices.count = 0)
{
No devices found
}
Else
{
Select the first connected device, at which time Selecteddevice.servicename is empty
Peerinformation selecteddevice = paireddevices[0];
Proactively create a Streamsocket
Streamsocket socket = new Streamsocket ();
The second parameter is a RFCOMM port number with a range of 1-30
Await socket. ConnectAsync (Selecteddevice.hostname, "1");
}
}
peerfinder.alternateidentities["BLUETOOTH:SDP"] = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; Find the use of Service Discovery Protocol (SDP) and pass the established The device that the GUID advertised the service
[C # code]
Search for a device with a specific GUID
Private async void AppToDevice2 ()
{
peerfinder.alternateidentities["BLUETOOTH:SDP"] = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
var paireddevices = await peerfinder.findallpeersasync ();
if (paireddevices.count = 0)
{
No devices found
}
Else
{
Select the first connected device
Peerinformation selecteddevice = paireddevices[0];
Proactively create a Streamsocket
Streamsocket socket = new Streamsocket ();
In this case selecteddevice.servicename equals the GUID you specify
Await socket. ConnectAsync (Selecteddevice.hostname, selecteddevice.servicename);
}
}
3) Listening for connection requests
[C # code]
Public Page1 ()
{
InitializeComponent ();
Listening for connection requests requires adding events first
Loaded + = mainpage_loaded;
}
void Mainpage_loaded (object sender, RoutedEventArgs e)
{
Triggered when a remote peer class is connected asynchronously
peerfinder.connectionrequested + = peerfinder_connectionrequested;
}
Async void Peerfinder_connectionrequested (object sender, Connectionrequestedeventargs args)
{
Get to the peer of the requesting connection
var peer = args. Peerinformation;
Responding to connections
var streamsocket = await Peerfinder.connectasync (peer);
}
4) Send a message
[C # code]
<summary>
Send a message when connected
</summary>
<param name= "Socket" ></param>
Public async void Send (streamsocket socket, string msg)
{
var _datawriter = new DataWriter (socket. OutputStream);
Length of Write message
UINT Strlength = _datawriter.measurestring (msg);
_datawriter.writeuint32 (strlength);
Writing the contents of a message
_datawriter.writestring (msg);
UINT numBytesWritten = await _datawriter.storeasync ();
}
5) Receive Message
[C # code]
<summary>
Read messages when connected
</summary>
<param name= "Socket" ></param>
Public async task<string> Read (streamsocket socket)
{
var _datareader = new DataReader (socket. InputStream);
Read message length
Await _datareader.loadasync (sizeof (UINT));
UINT Msglength = (UINT) _datareader.readuint32 ();
Reading the contents of a message
Await _datareader.loadasync (msglength);
Return _datareader.readstring (msglength);
}