65.9K
CodeProject 正在变化。 阅读更多。
Home

一个简单的蓝牙应用程序

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.64/5 (9投票s)

2013 年 12 月 5 日

CPOL
viewsIcon

47282

这个技巧将帮助你了解蓝牙功能以及如何使用其 API 开发一个简单的应用程序。

引言

如果你想知道如何使用蓝牙功能通过智能手机发送数据,那么你来对地方了。在这里,我们将一步一步地一起学习。

背景

蓝牙是一种无线通信技术,设备使用它在 10 米范围内相互通信。因此,我们必须在应用程序清单中包含 ID_CAP_PROXIMITYID_CAP_NETWORKING 功能。

Using the Code

首先,我们必须使用 PeerFinder 类发现其他设备和应用程序。

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();
    }
}

然后,应用程序搜索以查看它是否正在运行自身的实例。

public void Advertise()
{
    PeerFinder.DisplayName ="SuperMario";
    PeerFinder.Start();
}

现在,重要的是使用 StreamSocket 实例连接到对等应用程序。

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);
    }
} 

太棒了!所以我们想读取从另一个设备或对等应用程序传输的传入消息。这就是为什么我们使用 DataReader 类来加载和读取数据。

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); 

我们使用 DataWriter 类来向外部设备或对等应用程序发送传出消息。

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();

欢迎提出任何意见和建议。

© . All rights reserved.