我正在努力实现一个可连接BLE设备的Android应用,但是缺少适当的文档正在致死我。如果我运行该应用程序一次,但似乎没有两次以相同的方式工作,但是下次停止在某个地方(不知道在哪里),但是我得出的结论是我可能没有使用过disconnect()
和close()
以正确的顺序。
在我们说一个错误之后,我首先调用disconnect():
public void disconnect() {
mScanning = true;
mConnected = false;
startedConnect = false;
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
scanLeDevice(true);
return;
}
mBluetoothGatt.disconnect();
scanLeDevice(true);
}
然后我叫close():
public void close() {
if (mBluetoothGatt == null) {
return;
}
mBluetoothGatt.close();
mBluetoothGatt = null;
}
这是正确的方法还是错误的方法?请注意,我在断开连接后立即呼叫scanLeDevice(true);
,但随后又调用了close()
,我认为这只是“完成”所有操作并停止扫描了吗?
[通过在BluetoothGatt
上调用connectGatt
创建BluetoothDevice
对象时,您声明了蓝牙堆栈中32个(在当前的Android版本中)可用插槽之一。
在此对象上,现在您可以调用connect
和disconnect
更改“目标”的状态,如果Android应该尝试保持与设备的连接。在您致电disconnect
之前,Android将(永远)尝试连接到该设备并在由于某种原因断开连接后自动重新连接到该设备。在connect
之后再次调用disconnect
将使其尝试再次连接。
注意:在初始autoConnect
调用中将false
设置为connectGatt
将为首次隐式连接尝试设置初始超时(通常为30秒),如果设备连接并且稍后连接断开,它将不会t自动尝试重新连接。
因此BluetoothGatt
对象可以处于“已断开连接”状态,但仍占用Bluetooth堆栈中32个插槽之一。调用close
时,释放BluetoothGatt
对象的所有资源,并将插槽返回到Bluetooth堆栈。因此,闭合也暗含断开连接。要解决某些有问题的Android设备,可以在disconnect
之前调用BluetoothGatt
对象上的close
。请注意,一旦调用了close
,就无法在该BluetoothGatt
对象上调用任何其他方法。
注意:关闭蓝牙意味着自动破坏所有BluetoothGatt
对象。
回到您的问题,我不太了解您的BLE扫描与连接/断开连接/关闭。扫描与连接和BluetoothGatt
对象完全分开,并且连接和同时执行扫描没有问题。要停止扫描,请调用stopScan
上的BluetoothLeScanner
。