UWP Bluetooth RfcommDeviceService.FromIdAsync为null

问题描述 投票:0回答:1

我正在尝试使用以下代码连接到具有UWP的设备:

var devices = await DeviceInformation.FindAllAsync(BluetoothDevice.GetDeviceSelectorFromConnectionStatus(BluetoothConnectionStatus.Disconnected));
var device = devices.FirstOrDefault()
if (device != null && device.Name == "MyDevice")
{
    var rfcommService = await RfcommDeviceService.FromIdAsync(device.Id);
    var socket = new StreamSocket();
    await _socket.ConnectAsync(rfDeviceService.ConnectionHostName, rfDeviceService.ConnectionServiceName);
}

我设法找到我的设备,包含所有信息。

RfcommDeviceService.FromIdAsync(device.Id)总是返回null,因为它返回null如此之快,感觉事件不能“连接”或接收信息。

我的Package ApplicationManifest有以下与此有关的entites:

<Capabilities>
<Capability Name="internetClient" />
<DeviceCapability Name="bluetooth" />
<DeviceCapability Name="bluetooth.rfcomm">
  <Device Id="any">
    <Function Type="name:serialPort" />
  </Device>
</DeviceCapability>
<DeviceCapability Name="serialcommunication">
  <Device Id="any">
    <Function Type="name:serialPort" />
  </Device>
</DeviceCapability>

有人成功设法连接到蓝牙设备吗?

bluetooth uwp xamarin.uwp
1个回答
1
投票

从昨天开始寻找答案,我发帖后10米我找到了一个答案的例子。我只是在这里发布,以便其他人将来会发现:

var devices = await DeviceInformation.FindAllAsync(BluetoothDevice.GetDeviceSelectorFromConnectionStatus(BluetoothConnectionStatus.Disconnected));
var device = devices.FirstOrDefault()
if (device != null && device.Name == "MyDevice")
{
    var bluetoothDevice = await BluetoothDevice.FromIdAsync(device.Id);
    var rfcommServices = await bluetoothDevice.GetRfcommServicesForIdAsync(RfcommServiceId.FromUuid(RfcommServiceId.SerialPort.Uuid), BluetoothCacheMode.Uncached);
    if (rfcommServices.Services.Count > 0)
    {
        var service = rfcommServices.Services[0];
        await _socket.ConnectAsync(service.ConnectionHostName, service.ConnectionServiceName);
    }
}

可以肯定地写代码更漂亮,只是展示你如何让它工作:)

© www.soinside.com 2019 - 2024. All rights reserved.