SRS-XB01音箱是否为双协议栈?安卓Kotlin下扫描连接该设备如何实现
安卓Kotlin连接/扫描索尼SRS-XB01蓝牙音箱故障解决方案
协议栈确认
索尼SRS-XB01搭载的蓝牙4.2版本确实是双协议栈设计,同时支持两类蓝牙协议:
- 经典蓝牙(BR/EDR):用于日常音频传输,是设备正常工作时的主要通信协议
- BLE:仅用于配对引导、固件升级等低频场景,日常使用状态下BLE模块处于休眠状态,不会主动发送广播、也不接受常规GATT连接
之前方案无效的核心原因
BluetoothAdapter.startDiscovery()是经典蓝牙扫描接口,仅能捕获处于*可发现模式(即配对模式)*的设备响应,已经和本机配对的设备默认关闭可发现模式,自然不会被扫描到- BLE扫描、
connectGatt()调用无效是因为SRS-XB01的BLE功能仅在配对模式下激活,日常使用时无法被BLE扫描捕获,也无法建立GATT连接 - 第三方应用「Bluetooth Intensity」没有依赖扫描逻辑,而是直接读取系统已配对设备列表,对已建立经典蓝牙连接的设备主动调用RSSI读取接口实现数值采集
可落地的实现步骤
1. 权限配置
先在AndroidManifest中声明对应权限,注意动态申请危险权限:
- 安卓12及以上:需声明
BLUETOOTH_SCAN、BLUETOOTH_CONNECT权限 - 安卓11及更低版本:需声明
BLUETOOTH、BLUETOOTH_ADMIN、ACCESS_FINE_LOCATION权限
2. 无需扫描获取目标设备
直接读取系统已配对设备列表过滤出SRS-XB01,不需要调用扫描接口,避免扫描不到的问题:
val bluetoothAdapter = BluetoothAdapter.getDefaultAdapter() // 先判断蓝牙是否正常开启 if (bluetoothAdapter?.isEnabled == true) { // 获取所有已配对设备 val pairedDevices = bluetoothAdapter.bondedDevices // 过滤出目标音箱设备 val srsDevice = pairedDevices.firstOrNull { it.name == "SRS-XB01" } // 拿到设备对象后可进一步判断连接状态、读取RSSI }
3. 判断设备连接状态
通过A2DP蓝牙代理查询音箱是否和本机处于已连接状态:
bluetoothAdapter.getProfileProxy(context, object : BluetoothProfile.ServiceListener { override fun onServiceConnected(profile: Int, proxy: BluetoothProfile) { if (profile == BluetoothProfile.A2DP) { val connectedDevices = proxy.connectedDevices val isDeviceConnected = connectedDevices.any { it.address == srsDevice?.address } // 用完关闭代理,避免内存泄漏 bluetoothAdapter.closeProfileProxy(BluetoothProfile.A2DP, proxy) } } override fun onServiceDisconnected(profile: Int) {} }, BluetoothProfile.A2DP)
4. 定期读取RSSI值
注册广播接收器监听RSSI变化事件,每4秒触发一次RSSI读取即可实现和第三方应用相同的效果:
// 注册RSSI变化广播接收器 val rssiReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { if (intent?.action == BluetoothDevice.ACTION_RSSI_CHANGED) { val device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE) val rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI, Short.MIN_VALUE) // 过滤目标设备的RSSI结果 if (device?.address == srsDevice?.address) { Log.d("SRS-RSSI", "当前信号强度:$rssi dBm") } } } } context.registerReceiver(rssiReceiver, IntentFilter(BluetoothDevice.ACTION_RSSI_CHANGED)) // 定时4秒触发一次RSSI读取 val timer = Timer() timer.scheduleAtFixedRate(object : TimerTask() { override fun run() { // 仅已连接状态下调用readRssi才会返回有效结果 srsDevice?.takeIf { isDeviceConnected }?.readRssi() } }, 0, 4000)
补充说明
如果需要检测未连接的已配对音箱是否在附近,可以临时触发1~2秒的startDiscovery()扫描,即使设备未处于可发现模式,只要在范围内且蓝牙开启,扫描过程中也有概率返回设备查询结果,只是触发概率比配对模式低很多。
内容的提问来源于stack exchange,提问作者David
相关产品推荐
相关产品推荐

