Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if bluetooth is enabled on a device

I want to check if Bluetooth is enabled on a device (so that an app could use it without user interaction). Is there any way to do that? Can I also check Bluetooth and Bluetooth Low Energy separately?

like image 222
wasyl Avatar asked Dec 05 '22 02:12

wasyl


2 Answers

I accomplished this using the Radio class.

To check if Bluetooth is enabled:

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

To check if Bluetooth (in general) is supported:

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

If Bluetooth isn't installed, then there will be no Bluetooth radio in the radios list, and the LINQ query there will return null.

As for checking Bluetooth Classic and LE separately, I am currently investigating ways to do that and will update this answer when I know for certain that a way exists and works.

like image 134
Zenel Avatar answered Feb 03 '23 17:02

Zenel


Mixing @Zenel answer and new BluetoothAdapter class (from 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;
}

Desktop Warning: Radio.GetRadiosAsync() does not work on Desktop app compiled for different arch when running on, see the doc. You may use WMI as a workaround:

SelectQuery sq = new SelectQuery("SELECT DeviceId FROM Win32_PnPEntity WHERE service='BthLEEnum'");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(sq);
return searcher.Get().Count > 0;
like image 22
xmedeko Avatar answered Feb 03 '23 19:02

xmedeko