我一直在研究向廉价蓝牙耳机发送短音频消息的代码。
我希望能够使用 A2DP 选择当前的音频输出设备,并且似乎没有任何可靠的方法可以做到这一点。
我知道如何获取 A2DP 配置文件,并使用反射来连接和断开设备。
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
public BluetoothA2dp mA2DP;
mBluetoothAdapter.getProfileProxy(this, mProfileListener, BluetoothProfile.A2DP);
private BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener() {
public void onServiceConnected(int profile, BluetoothProfile proxy) {
if (profile == BluetoothProfile.A2DP) {
mA2DP = (BluetoothA2dp) proxy;
}
}
@Override
public void onServiceDisconnected(int profile) {
if (profile==BluetoothProfile.A2DP) {
mA2DP = null;
}
}
};
并且使用 A2DP 配置文件,您可以使用反射来访问连接和断开连接方法:
public void disconnectA2DP(BluetoothDevice bd) {
if (mA2DP==null) return;
try {
Method m = BluetoothA2dp.class.getDeclaredMethod("disconnect", BluetoothDevice.class);
m.invoke(mA2DP,bd);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
(除了使用“connect”作为方法名称之外,连接是相同的)
这一切都很好。然后,您可以使用GetConnectedDevices找出当前连接的设备。
旧款手机似乎只支持一个设备,因此这种机制适用于切换输出。但是,后来的手机(特别是三星)似乎同时支持两个设备。似乎没有任何方法可以选择音频将发送到哪个设备。我可以断开我不想要的那个,但有些设备有一个令人讨厌的习惯,即在不被询问的情况下重新连接,并使自己成为活动输出。
在BluetoothA2dp的源代码中,您可以清楚地看到“setActiveDevice”,但应用程序似乎无法访问它,即使通过反射也是如此。
任何帮助表示赞赏。
编辑:部分笨拙的解决方案:根据经验,设备列表中的最后一个 BluetoothDevice 是活动的。如果不是我想要的,我断开列表中的第一个,然后连接我想要的。这似乎可行,但并没有让我觉得是最好的解决方案。