如何获取已连接的Bluetooth蓝牙设备的具体类型
获取已配对蓝牙设备的具体类型
Android 框架自带的BluetoothDevice和BluetoothClass类提供了直接读取蓝牙设备类型的API,无需额外依赖。
前置权限要求
你需要先在AndroidManifest.xml中声明对应权限,否则调用接口会触发安全异常:
- 针对Android 12(API 31)及以上版本:
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
- 针对Android 11及以下版本:
<uses-permission android:name="android.permission.BLUETOOTH" />
注意:Android 12及以上的
BLUETOOTH_CONNECT是运行时权限,需要在代码中动态申请用户同意后才能使用。
实现代码
你可以直接在已获取的配对设备集合基础上,遍历读取每个设备的类型信息:
val pairedDevices: Set<BluetoothDevice> = mBluetoothAdapter.bondedDevices pairedDevices.forEach { device -> // 基础设备信息 val deviceName = device.name val macAddress = device.address // 获取设备类型封装类 val bluetoothClass = device.bluetoothClass // 读取设备大类 val majorClass = bluetoothClass.majorDeviceClass // 读取设备细分类型 val detailClass = bluetoothClass.deviceClass // 示例:判断设备具体类型 val deviceType = when (majorClass) { BluetoothClass.Device.Major.AUDIO_VIDEO -> when (detailClass) { BluetoothClass.Device.AUDIO_VIDEO_HEADPHONES -> "蓝牙耳机" BluetoothClass.Device.AUDIO_VIDEO_SPEAKER -> "蓝牙音箱" BluetoothClass.Device.AUDIO_VIDEO_HEADSET -> "蓝牙通话耳机" else -> "音视频类蓝牙设备" } BluetoothClass.Device.Major.PERIPHERAL -> when (detailClass) { BluetoothClass.Device.PERIPHERAL_KEYBOARD -> "蓝牙键盘" BluetoothClass.Device.PERIPHERAL_MOUSE -> "蓝牙鼠标" else -> "蓝牙外设" } BluetoothClass.Device.Major.PHONE -> "手机" BluetoothClass.Device.Major.COMPUTER -> "电脑" BluetoothClass.Device.Major.WEARABLE -> "可穿戴蓝牙设备" else -> "未知类型蓝牙设备" } // 输出信息 println("设备名:$deviceName,MAC地址:$macAddress,设备类型:$deviceType") }
如果你已经拿到了指定的已连接蓝牙设备对象,不需要遍历整个配对集合,直接对该对象调用bluetoothClass相关属性即可获取类型。
内容的提问来源于stack exchange,提问作者Sreeram Kallullathil
相关产品推荐
相关产品推荐

