在我们的应用程序中,我想使用 Android v4.2 或更高版本连接到之前配对的 A2DP 蓝牙扬声器并直接播放音频。
我可以使用以下代码成功创建 A2DP 配置文件对象来启动该过程:
/* Manifest permissions */
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
// Get the default adapter
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// Establish connection to the proxy.
mBluetoothAdapter.getProfileProxy(this, mProfileListener, BluetoothProfile.A2DP)
以及下面的监听器来响应连接:
private BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener() {
public void onServiceConnected(int profile, BluetoothProfile proxy) {
if (profile == BluetoothProfile.A2DP) {
mBluetoothSpeaker = (BluetoothA2dp) proxy;
// no devices are connected
List<BluetoothDevice> connectedDevices = mBluetoothSpeaker.getConnectedDevices();
//the one paired (and disconnected) speaker is returned here
int[] statesToCheck = {BluetoothA2dp.STATE_DISCONNECTED};
List<BluetoothDevice> disconnectedDevices = mBluetoothSpeaker.getDevicesMatchingConnectionStates(statesToCheck);
BluetoothDevice btSpeaker = disconnectedDevices.get(0);
//WHAT NOW?
}
}
public void onServiceDisconnected(int profile) {
if (profile == BluetoothProfile.A2DP) {
mBluetoothSpeaker = null;
}
}
};
对于现在要做什么,连接设备并将音频输出定向到它,我只是有点迷茫。我已尝试使用以下代码连接到设备,如 Android 文档中BluetoothSpeaker.getConnectedDevices()
所述,但最终调用未返回连接的设备。
BluetoothSocket tmp = null;
UUID MY_UUID = UUID.fromString("00001108-0000-1000-8000-00805f9b34fb");
try {
tmp = btSpeaker.createInsecureRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e1) {
// TODO Auto-generated catch block
Log.d("createRfcommSocketToServiceRecord ERROR", e1.getMessage());
}
mmSocket = tmp;
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
Log.d("connectException", connectException.getMessage());
mmSocket.close();
} catch (IOException closeException) { }
return;
}
connectedDevices = mBluetoothSpeaker.getConnectedDevices();
该代码似乎确实以某种方式连接到设备,因为当我停止执行时,蓝牙扬声器宣布它已准备好配对(就像它与音频源断开连接时一样)。
旧版本的BluetoothA2dp
似乎有一种connect(BluetoothDevice device)
方法,但现在已被删除(从 4.2 开始),我正在努力寻找任何明确的例子来说明如何以编程方式连接到 A2DP 设备,并将音频输出定向到它。任何有关如何处理的帮助都将不胜感激。
任何有关如何解决此问题的建议将不胜感激。