【问题标题】:Difference between close() and disconnect()?close() 和 disconnect() 之间的区别?
【发布时间】:2014-05-31 09:01:52
【问题描述】:

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

文档说:

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

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

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

【问题讨论】:

  • 我猜Close 表示你将不再使用 Gatt 对象

标签: android bluetooth bluetooth-lowenergy


【解决方案1】:

使用disconnect(),您可以稍后调用connect() 并继续该循环。

一旦您致电close(),您就完成了。如果您想再次连接,您必须再次拨打BluetoothDevice 上的connectGatt(); close() 将释放 BluetoothGatt 持有的所有资源。

【讨论】:

  • 超级有帮助 - 只打电话给disconnect() 并且一直用完 BT 接口,阻止任何新的连接。调用 close() 可以防止这种情况发生。
  • 每当我使用disconnect() 或close() 时,回调方法onConnectionStateChange 永远不会被调用来指示STATE_DISCONNECTED。
  • close() 不会调用 onConnectionStateChange,但 disconnect() 应该。当你调用 disconnect() 时,你确定你真的连接了吗?
  • @AlexanderFarber 你可以在没有 disconnect() 的情况下调用 close() 但根据我的经验你不会得到 onConnectionStateChange 回调。
  • 我也一直在与不一致的行为作斗争。如果你调用 gatt.close(),下次你连接到同一个设备时,你需要重做服务发现。绑定的 BTLE 设备不应该这样做。绑定的对等点知道你是谁(无论是配对还是是否或未启用特性)并且可以(按规范)立即发送任何数据。它会假设你知道它的服务。如果您完成了 gatt 关闭,您将不会知道它的服务并且可能会丢失该数据。我不知道 Android 在底层做了什么,但使用嵌入式低级堆栈肯定是这种情况。
【解决方案2】:

这里有一些值得深思的地方:

只要你没有在 Gatt 上调用 close,你仍然可以尝试连接它,或者发现它。所以当我尝试为一台机器发现服务时,我通常会运行一个线程或runnable,在一段时间内发出连接到机器的请求。

与机器连接的第一次尝试将返回一个 BluetoothGatt 对象,您以后可以使用该对象来尝试发现 BluetoothDevice 对象的服务。连接起来似乎很容易,但发现机器服务要困难得多。

mBluetoothGatt = machine.getDevice().connectGatt(this, false, mGattCallback);

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

mBluetoothGatt.discoverServices();

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

mBluetoothAdapter.cancelDiscovery();

这是一种用于连接我的可运行等的方法:

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();
}

最后,确保关闭所有已连接的 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);
}

【讨论】:

  • 当你实际调用close()而不是disconnect()时调用方法disconnectGatt有点令人困惑。
猜你喜欢
  • 1970-01-01
  • 2013-02-10
  • 2022-12-03
  • 2019-12-21
  • 2020-09-26
  • 2013-11-03
  • 1970-01-01
  • 1970-01-01
  • 2021-12-25
相关资源
最近更新 更多