【发布时间】:2020-04-02 15:20:17
【问题描述】:
我正在尝试制作一个连接到蓝牙心率监测器的应用。我搜索了很多文章和教程,但他们没有告诉你如何设置或详细了解蓝牙。 有人知道从哪里开始吗?
【问题讨论】:
标签: c# xamarin xamarin.android android-bluetooth
我正在尝试制作一个连接到蓝牙心率监测器的应用。我搜索了很多文章和教程,但他们没有告诉你如何设置或详细了解蓝牙。 有人知道从哪里开始吗?
【问题讨论】:
标签: c# xamarin xamarin.android android-bluetooth
您的意思是要使用 Xamarin.Android 连接到蓝牙串行设备吗?
如果是,
首先,在Android设备上抓取一个默认BluetoothAdapter的实例,并确定它是否已启用:
BluetoothAdapter adapter = BluetoothAdapter.DefaultAdapter;
if(adapter == null)
throw new Exception("No Bluetooth adapter found.");
if(!adapter.IsEnabled)
throw new Exception("Bluetooth adapter is not enabled.");
接下来,获取一个 BluetoothDevice 的实例,代表您要连接的物理设备。您可以使用适配器的 BondedDevices 集合获取当前配对设备的列表。我使用一些简单的 LINQ 来查找我正在寻找的设备:
BluetoothDevice device = (from bd in adapter.BondedDevices
where bd.Name == "NameOfTheDevice" select bd).FirstOrDefault();
if(device == null)
throw new Exception("Named device not found.");
最后,使用设备的CreateRfCommSocketToServiceRecord方法,会返回一个BluetoothSocket,可以用于连接和通信。请注意,下面指定的 UUID 是 SPP 的标准 UUID:
_socket = device.CreateRfcommSocketToServiceRecord(UUID.FromString("00001101-0000-1000-8000-00805f9b34fb"));
await _socket.ConnectAsync();
现在设备已连接,通过 BluetoothSocket 对象上的 InputStream 和 OutputStream 属性进行通信。这些属性是标准的 .NET Stream 对象,可以完全按照您的预期使用:
// Read data from the device
await _socket.InputStream.ReadAsync(buffer, 0, buffer.Length);
// Write data to the device
await _socket.OutputStream.WriteAsync(buffer, 0, buffer.Length);
【讨论】: