/**
* 蓝牙配对的回调接口
*/
public interface IBtConnectCallBack {
void onSucces();
void onFail();
}
private BluetoothAdapter mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
private BluetoothA2dp mBluetoothA2dp;
/**
* 蓝牙蓝牙设备,蓝牙与设备进行配对
*/
public void connectBluetoothA2DP(BluetoothDevice btDev, IBtConnectCallBack callBack) {
if (mBluetoothAdapter == null) {
return;
}
mBluetoothAdapter.getProfileProxy(context, new BluetoothProfile.ServiceListener() {
@Override
public void onServiceConnected(int profile, BluetoothProfile proxy) {
if (profile == BluetoothProfile.A2DP) {
//Service连接成功,获得BluetoothA2DP
mBluetoothA2dp = (BluetoothA2dp) proxy;
connectBlueToothAudio(btDev, callBack);
}
}
@Override
public void onServiceDisconnected(int profile) {
mBluetoothA2dp = null;
callBack.onFail();
}
}, BluetoothProfile.A2DP);
}
/**
* desc: 连接蓝牙音响
*/
public void connectBlueToothAudio(BluetoothDevice btDev, IBtConnectCallBack callBack) {
if (mBluetoothA2dp == null) {
callBack.onFail();
return;
}
LogUtil.w("A2DP sacn app 333333333333333333--》》》");
if (mBluetoothAdapter == null) {
callBack.onFail();
return;
}
if (btDev.getBondState() == BluetoothDevice.BOND_NONE) {
LogUtil.i("A2DP base_ac没有配对");
try {
//btDevice.createBond();
Method createBondMethod = BluetoothDevice.class.getMethod("createBond");
Boolean returnValue = (Boolean) createBondMethod.invoke(btDev);
} catch (Exception e) {
e.printStackTrace();
callBack.onFail();
}
}
int num = 0;
//蓝牙的连接配对是一个异步的过程,需要等待配对完成 等待5秒的配对时间
while (btDev.getBondState() != BluetoothDevice.BOND_BONDED && num <= 50) {
num++;//控制等待次数最多20次
SystemClock.sleep(200);
}
if (num > 50) {
callBack.onFail();
return;
}
try {
setPriority(btDev, 100); //设置priority
@SuppressLint("PrivateApi") Method connect = mBluetoothA2dp.getClass().getDeclaredMethod("connect", BluetoothDevice.class);
connect.setAccessible(true);
connect.invoke(mBluetoothA2dp, btDev);
connected = true;//连接标志
callBack.onSucces();
//getSocket(btDev);
} catch (Exception e) {
e.printStackTrace();
callBack.onFail();
}
}
使用
SppManager.connectBluetoothA2DP(device, new IBtConnectCallBack() {
@Override
public void onSucces() {
closeDialog();
}
@Override
public void onFail() {
closeDialog();
}
});