首先需要在清单文件添加权限:
<!-- 蓝牙权限 --> <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
获取当前连接蓝牙设备名称需要先获取已绑定或已匹配的蓝牙列表,然后再一个一个判断是否在连接状态,但是因为android现在将获取蓝牙设备连接状态的方法隐藏了,所以我们需要使用反射调用,下面是获取连接状态的源码:
/**
* Returns whether there is an open connection to this device.
* <p>Requires {@link android.Manifest.permission#BLUETOOTH}.
*
* @return True if there is at least one open connection to this device.
* @hide (注意这个,已隐藏)
*/
@SystemApi
@RequiresPermission(android.Manifest.permission.BLUETOOTH)
public boolean isConnected() {
final IBluetooth service = sService;
if (service == null) {
// BT is not enabled, we cannot be connected.
return false;
}
try {
return service.getConnectionState(this) != CONNECTION_STATE_DISCONNECTED;
} catch (RemoteException e) {
Log.e(TAG, "", e);
return false;
}
}
明白了这个后就好办了,下面是获取当前连接的蓝牙设备名称的方法代码:
private String getConnectedBtDevice() { //获取蓝牙适配器 BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); //得到已匹配的蓝牙设备列表 Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices(); if (bondedDevices != null && bondedDevices.size() > 0) { for (BluetoothDevice bondedDevice : bondedDevices) { try { //使用反射调用被隐藏的方法 Method isConnectedMethod = BluetoothDevice.class.getDeclaredMethod("isConnected", (Class[]) null); isConnectedMethod.setAccessible(true); boolean isConnected = (boolean) isConnectedMethod.invoke(bondedDevice, (Object[]) null); Log.e("123", "isConnected:" + isConnected); if (isConnected) { return bondedDevice.getName(); } } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } return null; }
还有一种通过
BluetoothProfile
而且要遍历各种 类型的额蓝牙设备 ,比如 音响 ,头戴,耳机,常用,等。
具体不显示 ,问 GPT
文章参考:
Android蓝牙连接蓝牙音箱和耳机的 A2dp与Headset Profile_a2dp和headset_小简木子的博客-CSDN博客