|
蓝牙连接总结
蓝牙4.0自动连接方法,很多小伙伴会可能会有连接不稳定、不会重连或重连不上等等问题,下面就是我关于自动连接的一点小技巧,大家可参考参考。
蓝牙连接方法:
以前:
连接分三星和非三星手机,根据设备mac地址直接生成device,三星手机直接连,调用justConnect();非三星手机,调用connectGatt();
public void connectGatt () {
if (bluetoothDevice != null) {
if (mBluetoothGatt != null) {
mBluetoothGatt.close();
mBluetoothGatt.disconnect();
mBluetoothGatt = null;
}
mBluetoothGatt = bluetoothDevice.connectGatt(this.context, false,
gattCallback);
mBluetoothGatt.connect();
} else {
Log.e(tagString,
"the bluetoothDevice is null, please reset the bluetoothDevice");
}
}
public void justConnect() {
if (mBluetoothGatt != null) {
mBluetoothGatt.connect();
} else {
connectGatt();
}
}
以前判断连接,是在发现服务后就判断连接,但这会导致假链接或服务不全。
断开连接后,三星手机直接调用justConnect()方法,非三星手机调用connectGatt,并30秒调用一次。
总结:上面的连接方法有机率引起手机与设备之间的连接通道崩溃、假链接或服务不全。
现在优化后的方法:
加上
// 清除连接信息
private boolean refreshGattStructure(BluetoothGatt gatt) {
BluetoothGatt localGatt = gatt;
try {
Method localMethod = localGatt.getClass().getMethod("refresh",
new Class[0]);
if (localMethod != null) {
boolean result = ((Boolean) localMethod.invoke(localGatt,
new Object[0])).booleanValue();
return result;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
连接方法变成了:
public void connectGatt() {
if (bluetoothDevice != null) {
if (mBluetoothGatt != null) {
refreshGattStructure(mBluetoothGatt);
}
handler.postDelayed(connectGattRunnable, 30);
} else {
Log.e(tagString,
"the bluetoothDevice is null, please reset the bluetoothDevice");
}
}
//修改删除remove:
public void remove() {
if (mBluetoothGatt != null) {
mBluetoothGatt.close();
refreshGattStructure(mBluetoothGatt);
mBluetoothGatt = null;
}
bluetoothDevice = null;
readChar = null;
deviceChar = null;
writeChar = null;
}
连接上的判断方法也改成所有服务都找到,才算连接上了。
断开连接,简洁为断开后,启动扫描,扫描到对应设备就连接,连接ok后,判断是不是所有的设备都连上了,若是,则停止扫描。
10月22日 本周六晚上8点,王老师将对蓝牙一对多(二)进行讲解,现场直播,如果有其它问题的也可以问王老师,王老师都会一一解答。欢迎大家前来捧场!
报名方式:加群554029215,加群后联系项目对接-casey报名
|
|