A Simple Bluetooth Application






4.64/5 (9 votes)
This tip enables you to discover bluetooth features and how we can use its API to develop a simple application.
Introduction
If you want to know how to use the Bluetooth features to send data using your SmartPhone, you are at the right place. Here, we will learn that together step by step.
Background
Bluetooth is a wireless communication technology that devices use to communicate with each other within just a 10 meter. So we must include ID_CAP_PROXIMITY
and ID_CAP_NETWORKING
capabilities in our application manifest.
Using the Code
First of all, we must discover other devices and applications using the PeerFinder
class.
StreamSocket socket;//socket is created to enable app-to-app and app-to-device communication
public async void FindPeers()
{
// find other devices
IReadOnlyList<PeerInformation> peers = await PeerFinder.FindAllPeersAsync();
if (peers.Count > 0)
{ // establish connection with the fist peer
socket = await PeerFinder.ConnectAsync(peers[0]); // stop finding
// in order to conserve battery life
// stop finding in order to conserve battery life
PeerFinder.Stop();
}
}
Then, the application searches to see if it is running an instance of itself.
public void Advertise()
{
PeerFinder.DisplayName ="SuperMario";
PeerFinder.Start();
}
Now, it is important to use the StreamSocket
instance to connect to the peer application.
public void MySampleApp()
{
PeerFinder.ConnectionRequested += PeerFinder_connexionRequested;
}
private void PeerFinder_connexionRequested
(object sender, ConnectionRequestedEventArgs args)
{
MessageBoxResult result = MessageBox.Show
(string.Format("{0} is trying to connect.
Would you like to accept?",args.PeerInformation.DisplayName),
"My bleutooth Chat App",MessageBoxButton.OKCancel );
if (result == MessageBoxResult.OK)
{
socket.Connect(args.PeerInformation);
}
}
Great! So we want to read the incoming messages that are transmitted from another device or peer applications. That is why we use the DataReader
class to load and read data.
DataReader dataReader = new DataReader(socket.InputStream);
await dataReader.loadAsync(4);// get the size of message
uint messageLen =(uint)DataReader.readInt32();
await dataReader.loadAsync(messageLen)//send the message
String Message = dataReader.ReadString(messageLen);
And we use the DataWriter
class in order to send outgoing messages to an external device or peer application.
DataWriter dataWriter = new DataWriter(socket.OutputStream);
// send the message length first
dataWriter.WriteInt32(Message.length);
await dataWriter.StoreAsync();
//send the actual message
dataWriter.WriteString(message);
await dataWriter.StoreAsync();
Any comments are most welcome.