【问题标题】:Unable to Discover Bluetooth Devices in UWP application but works in WPF application无法在 UWP 应用程序中发现蓝牙设备,但在 WPF 应用程序中工作
【发布时间】:2021-03-16 12:16:58
【问题描述】:

我正在尝试使用以下代码使用32feet.NET 库扫描蓝牙设备。

private void Button_Click(object sender, RoutedEventArgs e)
{
    BluetoothClient client = new BluetoothClient();
    foreach (BluetoothDeviceInfo bdi in client.DiscoverDevices())
    {
        System.Diagnostics.Debug.WriteLine(bdi.DeviceName + " " + bdi.DeviceAddress);
    }
}

以上代码返回 WPF 应用程序中可用蓝牙设备的列表。但是当我在 UWP 应用程序中使用相同的代码时,我得到了以下异常。

System.Runtime.InteropServices.COMException: '在意外的时间调用了一个方法。

当我按照here 的建议尝试使用 async/await 来修复此异常时,我无法在集合中使用 async/await。所以我使用了 Task.FromResult 方法如下,那么异常也没有修复。

private async void Button_Click(object sender, RoutedEventArgs e)
{
    BluetoothClient client = new BluetoothClient();
    var dev = await Task.FromResult(client.DiscoverDevices());
            
    foreach (BluetoothDeviceInfo bdi in dev)
    {
      System.Diagnostics.Debug.WriteLine(bdi.DeviceName + " " + bdi.DeviceAddress);
    }
 }

谁能帮我解释为什么相同的代码在 WPF 应用程序中有效,但在 UWP 应用程序中无效?

【问题讨论】:

    标签: xamarin.forms uwp bluetooth rfcomm 32feet


    【解决方案1】:

    无法在 UWP 应用程序中发现蓝牙设备,但在 WPF 应用程序中有效

    恐怕第三方库不支持UWP平台,如果你想在UWP平台发现蓝牙设备,建议你使用DeviceWatcher类枚举所有蓝牙设备。

    Here是官方代码示例,你可以参考,here是官方文档。

    【讨论】:

      猜你喜欢
      • 2018-05-22
      • 2016-06-10
      • 2019-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-25
      • 1970-01-01
      • 2021-07-27
      相关资源
      最近更新 更多