2015-10-08 119 views
5

我想檢查設備上是否啓用了藍牙(以便應用程序可以在沒有用戶交互的情況下使用它)。有沒有辦法做到這一點?我是否也可以單獨檢查藍牙和藍牙低功耗?如何檢查設備上是否啓用了藍牙

回答

2

有沒有辦法做到這一點?我是否也可以單獨檢查藍牙和藍牙低功耗?

你是什麼意思的「設備」,它是應用程序運行的設備,或設備承載應用程序需要訪問的藍牙服務?

據我所知,UWP中沒有API來檢查設備是否啓用了藍牙。

在Windows Mobile設備上,可以採用以下方法作爲解決方法。

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

在Windows PC設備上,我建議您檢查藍牙服務級別的服務可訪問性,作爲解決方法。

對於像RFCOMM這樣的非BLE服務,您可以獲得具有特定服務ID的設備的計數。如果藍牙在硬件級別禁用,計數爲0。

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

對於BLE服務,您可以使用BluetoothLEAdvertisementWatcher類接收的BLE廣告。如果藍牙在硬件級別被禁用,則不會收到廣告。

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(); 
     } 
+0

添加處理程序'watcher.Stopped'如果BLE不可用,你有'args.Error == BluetoothError .RadioNotAvailable'。 – xmedeko

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

要檢查是否支持藍牙(一般):

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

如果沒有安裝藍牙,然後就沒有藍牙無線電在無線電列表中,並且LINQ查詢將返回null。

至於藍牙Classic和LE分開檢查,我目前正在研究如何做到這一點,並會在我確定某種方式存在並正常工作時更新此答案。

1

混合@Zenel答案和新BluetoothAdapter類(從10場創作者更新):

/// <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; 
    var radios = await Radio.GetRadiosAsync(); 
    var radio = radios.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; 
} 
相關問題