随后在BLE Android应用程序中正确调用方法connect()和close()吗?

问题描述 投票:0回答:1

我正在努力实现一个可连接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(),我认为这只是“完成”所有操作并停止扫描了吗?

java android bluetooth-lowenergy android-bluetooth bluetooth-gatt
1个回答
0
投票

[通过在BluetoothGatt上调用connectGatt创建BluetoothDevice对象时,您声明了蓝牙堆栈中32个(在当前的Android版本中)可用插槽之一。

在此对象上,现在您可以调用connectdisconnect更改“目标”的状态,如果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

© www.soinside.com 2019 - 2024. All rights reserved.