Android蓝牙A2dp profile的使用

时间:2022-01-31 21:10:47

A2dp profile是android支持的一种蓝牙情景模式,一般用于蓝牙立体声耳机,即蓝牙音频的输出

在android的app层中,A2dp的使用并不是很开放,api只提供了非常少的操作接口,连基本的连接都只能用反射来调用底层的方法。a2dp的使用是通过BluetoothA2dp这个代理类来控制A2dp服务的,这里简单举例使用的方法:

private BluetoothAdapter mBluetooth = BluetoothAdapter.getDefaultAdapter();
mBluetooth.getProfileProxy(this, new profileListener(), BluetoothProfile.A2DP); public class profileListener implements ServiceListener {
@Override
public void onServiceConnected(int profile, BluetoothProfile proxy) {
// TODO Auto-generated method stub
Log.i(TAG, "onServiceConnected()");
mBluetoothProfile = proxy;
mHandler.sendEmptyMessage(MESSAGE_A2DP_PROXY_CHANGED);
} @Override
public void onServiceDisconnected(int profile) {
// TODO Auto-generated method stub
Log.i(TAG, "onServiceDisconnected()");
}
}

该profile的连接和断开的方法在Android源码中有定义,因此可以通过反射来获取到接口:

public void a2dpConnect(BluetoothDevice device){
BluetoothA2dp a2dp = (BluetoothA2dp) mBluetoothProfile;
a2dp.isA2dpPlaying(device);
Class<? extends BluetoothA2dp> clazz = a2dp.getClass();
Method m2;
try {
Log.i(TAG,"use reflect to connect a2dp");
m2 = clazz.getMethod("connect",BluetoothDevice.class);
m2.invoke(a2dp, device);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e(TAG,"error:" + e.toString());
}
}

另外需要注意的是,由于使用了反射的方法,并非适用于所有版本的android系统,4.2.2以上的连接的成功率还是较高的;同时,在获取连接的状态上,也并非所有的系统都能或得到正确的状态,有些系统或硬件平台不支持该profile的操作,所以在实际使用时,要因地制宜,因机而异。