How to check if bluetooth is enabled on a device

▼魔方 西西 提交于 2020-02-28 05:53:47

问题


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?


回答1:


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.




回答2:


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;



回答3:


Is there any way to do that? Can I also check Bluetooth and Bluetooth Low Energy separately?

What do you mean by “device”, is it the device that the app runs on, or the device host the Bluetooth service that the app need to access?

As far as I know, there is no API in UWP to check whether the Bluetooth is enabled on the device.

On the Windows Mobile device, you can use the following way as a workaround.

private async void FindPaired()
{
    // Search for all paired devices
    PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";

    try
    {
        var peers = await PeerFinder.FindAllPeersAsync();

        // Handle the result of the FindAllPeersAsync call
     }
     catch (Exception ex)
     {
         if ((uint)ex.HResult == 0x8007048F)
         {
             MessageBox.Show("Bluetooth is turned off");
         }
     }
 }

On the Windows PC device, I suggest you checking the services accessibility in the Bluetooth service level as a workaround.

For non-BLE services like RFCOMM, you can get the count of the devices with a specific service id. If the Bluetooth is disabled in hardware level, the count will be 0.

rfcommServiceInfoCollection = await DeviceInformation.FindAllAsync(
    RfcommDeviceService.GetDeviceSelector(RfcommServiceId.ObexObjectPush));

For the BLE services, you can use BluetoothLEAdvertisementWatcher class to receive the BLE advertisement. If the Bluetooth is disabled in hardware level, no advertisement will be received.

watcher = new BluetoothLEAdvertisementWatcher();
watcher.Received += OnAdvertisementReceived;

        private async void OnAdvertisementReceived(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementReceivedEventArgs eventArgs)
        {
            var address = eventArgs.BluetoothAddress;
            BluetoothLEDevice device = await BluetoothLEDevice.FromBluetoothAddressAsync(address);
            var cnt =device.GattServices.Count;
            watcher.Stop();
        }


来源:https://stackoverflow.com/questions/33013275/how-to-check-if-bluetooth-is-enabled-on-a-device

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!