最近一直在开发经典蓝牙,搞得头疼,网上资料太少。
参考链接:https://www.jianshu.com/p/94f8e3119981
https://www.bbsmax.com/A/WpdKB7Pr5V/
我需要在app中连接经典蓝牙用来播放歌曲,以及来录音。
在网上搜索经典蓝牙的连接,一大堆都是这种
val socket =
device.createInsecureRfcommSocketToServiceRecord(
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"))
println("连接服务端...")
socket.connect()
println("连接建立...")
但是这个连接上了之后一段时间不通信,就会自动断开,而且连接这个之后,播放音乐还是从手机的喇叭出来的。。
于是找了一下,看到了上面两片文章,音频使用a2dp来连接。
先看一下广播:
private BroadcastReceiver mBluetoothBroadcast = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction() == null) {
return;
}
switch (intent.getAction()) {
case BluetoothDevice.ACTION_BOND_STATE_CHANGED:
int bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.BOND_NONE);
switch (bondState) {
case BluetoothDevice.BOND_BONDED: //配对成功
a2dpConnect(mBluetoothDevice); //连接蓝牙设备
break;
case BluetoothDevice.BOND_NONE:
mBluetoothDevice.createBond();
break;
default:
break;
}
break;
case BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED:
if (intent.getIntExtra(BluetoothA2dp.EXTRA_STATE, -1) == BluetoothA2dp.STATE_CONNECTED) {
Toast.makeText(context, "绑定成功", Toast.LENGTH_SHORT).show();
}
break;
case AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED:
int state = intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, -1);
if (AudioManager.SCO_AUDIO_STATE_CONNECTED == state) {
mAudioManager.setBluetoothScoOn(true);
//开启录音~
}
break;
}
}
};
先获取a2dp对象
mBluetoothAdapter.getProfileProxy(this, new BluetoothProfile.ServiceListener() {
@Override
public void onServiceConnected(int profile, BluetoothProfile proxy) {
if (profile == BluetoothProfile.A2DP) {
mBluetoothA2dp = (BluetoothA2dp) proxy;
}
}
@Override
public void onServiceDisconnected(int profile) {
}
}, BluetoothProfile.A2DP);
然后判断A2DP连接上没有
public boolean getA2dpState(BluetoothDevice device) {
return mBluetoothA2dp != null && mBluetoothA2dp.getConnectionState(device) ==
BluetoothProfile.STATE_CONNECTED;
}
连接成功,就开始录音或者播放音乐:
mAudioManager.stopBluetoothSco();
mAudioManager.startBluetoothSco();
没有连接成功就先配对设备,然后连接
mBluetoothDevice.createBond(); //配对设备
public void a2dpConnect(BluetoothDevice device) {
if (mBluetoothA2dp != null) {
Class<? extends BluetoothA2dp> clazz = mBluetoothA2dp.getClass();
Method m2;
try {
Log.i(TAG, "use reflect to connect a2dp");
m2 = clazz.getMethod("connect", BluetoothDevice.class);
m2.invoke(mBluetoothA2dp, device);
} catch (Exception e) {
Log.e(TAG, "error:" + e.toString());
}
}
}
然后这些事件的回调都在那个广播中收到。。。