首页 > 解决方案 > 如何以编程方式在android上的蓝牙音频设备之间切换音频

问题描述

让我困惑了很久。

我在 android 手机上连接了两个 bt 音频设备,我想以编程方式切换特定的 bt 音频设备。

我搜索关于 a2dp、媒体路由器和 audioManager 的关键字似乎不能做这件事......

我唯一发现的功能是:

BT 设备=> A 和 B 连接在 Android 手机上。现在媒体播放到 A 我想切换到 B

Step1:A、B在Android手机上解除配对。

步骤 2:Android 手机上的一对。

Step3:B对Android手机。

媒体播放输出为B,

似乎最近的一对蓝牙设备是媒体播放输出。

谁能给我一些建议或方向?多谢你们

标签: javaandroidkotlinbluetooth

解决方案


文档说它一次只能连接到单个 A2DP 设备,因此您应该能够通过连接到要使用的设备在设备之间切换。您可以使用BluetoothSockets连接到设备。

编辑:我找到了其他解决方案,我认为这是可靠的。它们都依赖于方法反射。

第一个来自这篇文章。1.从serviceListener获取BluetoothA2dp代理

bluetoothManager.adapter.getProfileProxy(this, serviceListener, BluetoothProfile.A2DP)

private val serviceListener = object : BluetoothProfile.ServiceListener {
    override fun onServiceDisconnected(profile: Int) {
        if (profile == BluetoothProfile.A2DP) {
            bluetoothA2dp = null
        }
    }

    override fun onServiceConnected(profile: Int, proxy: BluetoothProfile?) {
        if (profile == BluetoothProfile.A2DP) {
            handler.post(btSearchRunnable)
            bluetoothA2dp = proxy as BluetoothA2dp
        }
    }
}
  1. 从反射中获取“连接”方法。

    private val connect = BluetoothA2dp::class.java.getDeclaredMethod("connect",BluetoothDevice::class.java)
    
  2. 使用代理作为第一个参数和设备作为第二个参数调用方法。

    connect.invoke(蓝牙A2dp,设备)

其他方法使用反射来获取 createRfcommSocket 以规避您通常无法访问的一个参数的问题。我可以发布它的链接,但我遇到的问题是主线程总是滞后,总是给我一个错误并且无法预测地连接。


推荐阅读