获取已连接蓝牙LE设备的列表

时间:2014-10-21 19:24:02

标签: android bluetooth bluetooth-lowenergy android-5.0-lollipop

我是蓝牙低功耗(LE)API的新手。有没有办法检查Android设备当前是否连接到任何蓝牙LE设备,并可能获得这些设备的列表?

BT-LE设备实际上是否“连接”?我注意到当我的智能手表与我的Nexus 5配对/连接时,蓝牙图标在状态栏(在KitKat上)不会变成白色/粗体,就像连接到传统蓝牙设备时一样。

我使用下面的代码来表示经典设备。看起来我可以用相同的方式检查GATT和GATT_SERVER,但它们总是返回断开状态。

更新:所以现在我已经将Android Lollipop闪存到了我的Nexus 5,我发现它必须以某种方式存在,因为它用于SmartLock,并且它以某种方式检测到我的BT-LE Android手表已连接。

private BluetoothAdapter getBTAdapter() {       
    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN_MR2)
        return BluetoothAdapter.getDefaultAdapter();
    else {
        BluetoothManager bm = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
        return bm.getAdapter();
    }
}

public boolean isBluetoothConnected() {
    if(mBluetoothAdapter == null || 
            (mBluetoothAdapter.getProfileConnectionState(BluetoothProfile.HEADSET) == BluetoothProfile.STATE_DISCONNECTED 
                && mBluetoothAdapter.getProfileConnectionState(BluetoothProfile.A2DP) == BluetoothProfile.STATE_DISCONNECTED
                && mBluetoothAdapter.getProfileConnectionState(BluetoothProfile.HEALTH) == BluetoothProfile.STATE_DISCONNECTED)

            ) {

        Utils.logDebug(TAG, "GATT_SERVER " + mBluetoothAdapter.getProfileConnectionState(BluetoothProfile.GATT_SERVER));
        Utils.logDebug(TAG, "GATT " + mBluetoothAdapter.getProfileConnectionState(BluetoothProfile.GATT));
        return false;
    }
    return true;
}

2 个答案:

答案 0 :(得分:2)

您可以使用:

BluetoothManager bluetoothManager = (BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE);
List<BluetoothDevice> devices = bluetoothManager.getConnectedDevices(BluetoothProfile.GATT);
for(BluetoothDevice device : devices) {
  if(device.getType() == BluetoothDevice.DEVICE_TYPE_LE) {
     ...
  }
}

如果您的手表实际已连接,我无法接听。可能是你的手表只宣传它的状态,手机正在收听这个广告。这取决于它的实施方式。

答案 1 :(得分:0)

您的BTLE设备可以使用系统中的其他配置文件进行注册。 Android的API仅公开一些配置文件(GATT,GATT_SERVER,Headset等)。但是,还有其他配置文件可以像系统一样注册,例如INPUT_DECVICE。调用getConnectedDevices()仅适用于GATT和GATT_SERVER配置文件,但如果您的设备已注册为任何其他配置文件,则该方法无法正常工作。