close()和disconnect()之间的区别?

Art*_*ans 43 android bluetooth bluetooth-lowenergy

Android的蓝牙低功耗API实现1种方法连接到该设备connectGatt(),但2种方法来关闭连接disconnect()close().

文件说:

  • disconnect():断开已建立的连接,或取消当前正在进行的连接尝试.

  • close():应用程序应在使用此GATT客户端完成后尽早调用此方法.

BluetoothGatt.java的源代码显示close()取消注册应用程序,disconnect()断开客户端连接.然而,它没有说明实际意味着什么.我的意思是,如果只有一种方法可以连接到客户端,为什么有两种方法可以关闭/断开连接?

Dou*_*nes 66

随后disconnect()您可以调用connect()并继续该循环.

一旦打电话,close()你就完成了.如果您想再次连接,你将不得不调用connectGatt()BluetoothDevice再次; close()将释放所持有的任何资源BluetoothGatt.

  • 每当我使用`disconnect()`或`close()`时,回调方法`onConnectionStateChange`永远不会被调用,表明STATE_DISCONNECTED. (8认同)
  • 超级有用 - 只是调用`disconnect()`并且不断运行BT接口以防止任何新连接.调用`close()`会阻止这种情况. (4认同)
  • close()不会调用onConnectionStateChange,但是connect()应该会。您确定在调用disconnect()时确实连接了吗? (2认同)
  • @AlexanderFarber您可以调用close()而不使用disconnect(),但是根据我的经验,您不会得到onConnectionStateChange回调。 (2认同)
  • 我也一直在与不一致的行为作斗争。如果您调用 gatt.close(),下次连接到同一设备时,您将需要重做服务发现。绑定的 BTLE 设备不应该这样做。绑定的对等方知道您是谁(无论是配对还是是否或未启用特性)并且可以(根据规范)立即发送任何数据。它将假设您了解其服务。如果您关闭了关贸总协定,您将不知道其服务并可能会丢失该数据。我不知道 Android 在低端做了什么,但使用嵌入式低级堆栈时情况肯定是这样。 (2认同)

Dro*_*ris 13

这是一些值得思考的东西:

只要你没有在Gatt上打电话,你仍然可以尝试连接它或发现.因此,当我尝试为机器发现服务时,我通常会运行一个线程或runnable,使请求连接到机器一段时间.

第一次使用机器连接尝试将返回一个BluetoothGatt对象,您可以在以后使用该对象尝试发现BluetoothDevice对象的服务.它似乎很容易连接,但更难发现机器的服务.

mBluetoothGatt = machine.getDevice().connectGatt(this, false, mGattCallback);
Run Code Online (Sandbox Code Playgroud)

所以在我的线程/ runnable中,我将检查BluetoothGatt是否为空.如果是,我将再次调用上面的代码行,否则我将尝试发现BluetoothGatt服务.

mBluetoothGatt.discoverServices();
Run Code Online (Sandbox Code Playgroud)

哦,我总是确保在尝试连接发现服务之前调用BluetoothAdapter.cancelDiscovery().

mBluetoothAdapter.cancelDiscovery();
Run Code Online (Sandbox Code Playgroud)

这是一个方法用于连接我的runnable等:

public void connectToMachineService(BLEMachine machine) {
    Log.i(SERVICE_NAME, "ATTEMPTING TO CONNECT TO machine.getDevice().getName());

    mBluetoothAdapter.cancelDiscovery();

    if(mBluetoothGatt == null)
        mBluetoothGatt = machine.getDevice().connectGatt(this, false, mGattCallback);
    else
        mBluetoothGatt.discoverServices();
}
Run Code Online (Sandbox Code Playgroud)

最后,确保关闭所有已连接的BluetoothGatt对象.似乎Android可以在开始说"无法连接到Gatt服务器"或其他类似的东西之前处理五个BluetoothGatt对象.

在我创建的每个BluetoothGatt上,我将在其上调用close然后广播更新,说明连接已关闭.似乎有很多次BluetootGatt在断开状态时不会响应状态变化.我关闭BluetoothGatt的方法是这样的.我让方法打开,以便Activity调用服务并断开连接,如果一台机器没有响应并且没有调用断开连接状态.

public void disconnectGatt(BluetoothGatt gatt) {
    if(gatt != null) {
        gatt.close();
        gatt = null;
    }

    broadcastUpdate(ACTION_STATE_CLOSED);
}
Run Code Online (Sandbox Code Playgroud)

  • 当您实际调用“close()”而不是“disconnect()”时,调用方法“disconnectGatt”有点令人困惑。 (2认同)