如何检查设备上是否启用了蓝牙

was*_*syl 4 bluetooth win-universal-app windows-10 uwp

我想检查设备上是否启用了蓝牙(以便应用程序可以在没有用户交互的情况下使用它).有没有办法做到这一点?我还可以单独检查蓝牙和蓝牙低功耗吗?

小智 8

我用这个Radio课完成了这个.

要检查蓝牙是否已启用:

public static async Task<bool> GetBluetoothIsEnabledAsync()
{
    var radios = await Radio.GetRadiosAsync();
    var bluetoothRadio = radios.FirstOrDefault(radio => radio.Kind == RadioKind.Bluetooth);
    return bluetoothRadio != null && bluetoothRadio.State == RadioState.On;
}
Run Code Online (Sandbox Code Playgroud)

要检查是否支持蓝牙(通常):

public static async Task<bool> GetBluetoothIsSupportedAsync()
{
    var radios = await Radio.GetRadiosAsync();
    return radios.FirstOrDefault(radio => radio.Kind == RadioKind.Bluetooth) != null;
}
Run Code Online (Sandbox Code Playgroud)

如果未安装蓝牙,则无线电列表中将不会有蓝牙无线电,并且LINQ查询将返回null.

至于单独检查蓝牙经典和LE,我正在研究如何做到这一点,并且当我确定某种方式存在并且有效时,将更新这个答案.


xme*_*eko 5

混合@Zenel答案和新BluetoothAdapter类(来自Win 10 Creators Update):

/// <summary>
/// Check, if any Bluetooth is present and on.
/// </summary>
/// <returns>null, if no Bluetooth LE is installed, false, if BLE is off, true if BLE is on.</returns>
public static async Task<bool?> IsBleEnabledAsync()
{
    BluetoothAdapter btAdapter = await BluetoothAdapter.GetDefaultAsync();
    if (btAdapter == null)
        return null;
    if (!btAdapter.IsCentralRoleSupported)
        return null;
    // for UWP
    var radio = await btAdapter.GetRadioAsync();
    // for Desktop, see warning bellow
    var radios = await Radio.GetRadiosAsync().FirstOrDefault(r => r.Kind == RadioKind.Bluetooth);
    if (radio == null)
        return null; // probably device just removed
    // await radio.SetStateAsync(RadioState.On);
    return radio.State == RadioState.On;
}
Run Code Online (Sandbox Code Playgroud)

桌面警告: Radio.GetRadiosAsync()运行时不适用于为不同架构编译的桌面应用程序,请参阅文档。您可以使用 WMI 作为解决方法:

SelectQuery sq = new SelectQuery("SELECT DeviceId FROM Win32_PnPEntity WHERE service='BthLEEnum'");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(sq);
return searcher.Get().Count > 0;
Run Code Online (Sandbox Code Playgroud)