Android应用如何获取当前已连接蓝牙设备而非仅配对设备
获取当前已连接的蓝牙设备
BLUETOOTHADAPTER.getbondeddevice()只能获取历史配对过的设备,要获取当前处于连接状态的设备,可通过以下方式实现:
方法1:通过BluetoothManager直接获取(Android 12+)
Android 12(API 31)及以上版本提供了更直接的API,可指定蓝牙协议类型获取已连接设备:
// 获取BluetoothManager实例 BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); // 获取已连接的BLE设备(GATT协议) List<BluetoothDevice> connectedGattDevices = bluetoothManager.getConnectedDevices(BluetoothProfile.GATT); // 若要获取音频类已连接设备,可替换为对应Profile List<BluetoothDevice> connectedAudioDevices = bluetoothManager.getConnectedDevices(BluetoothProfile.A2DP);
方法2:兼容低版本的Profile代理方式(Android < 12)
对于Android 12以下的系统,需要通过蓝牙Profile代理获取已连接设备:
BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); bluetoothManager.getAdapter().getProfileProxy(this, new BluetoothProfile.ServiceListener() { @Override public void onServiceConnected(int profile, BluetoothProfile proxy) { // 获取当前该协议下的已连接设备列表 List<BluetoothDevice> connectedDevices = proxy.getConnectedDevices(); // 在此处理已连接设备数据 // 使用完毕后务必关闭代理,避免资源泄漏 bluetoothManager.getAdapter().closeProfileProxy(profile, proxy); } @Override public void onServiceDisconnected(int profile) { // 处理服务意外断开的情况 } }, BluetoothProfile.GATT); // 根据需求替换为A2DP/HEADSET等Profile
注意事项
- 不同
BluetoothProfile对应不同蓝牙用途:BluetoothProfile.GATT:BLE低功耗设备BluetoothProfile.A2DP:音频播放设备(如蓝牙耳机)BluetoothProfile.HEADSET:通话类蓝牙设备
- 权限要求:
- Android 12+:需声明并动态申请
BLUETOOTH_CONNECT权限 - Android 11及以下:需声明
BLUETOOTH、BLUETOOTH_ADMIN权限
- Android 12+:需声明并动态申请
内容的提问来源于stack exchange,提问作者Faizan NAZIR
相关产品推荐
相关产品推荐

