【问题标题】:Android BLE (Bluetooth Low Energy) Connect/Disconnect/ReconnectAndroid BLE(蓝牙低功耗)连接/断开/重新连接
【发布时间】:2017-08-08 22:34:28
【问题描述】:

Android BLE API 看起来很奇怪,也许我遗漏了一些东西。我需要做的是与 BLE 设备建立连接,然后如果有一段时间空闲,则暂时断开连接,但当用户想要做一些新的事情时,我想重新连接。

首先要连接,我调用:

Gatt1 = Device.ConnectGatt (Android.App.Application.Context, false, GattCallback);

然后我正在考虑暂时断开我的通话

Gatt1.Disconnect();

然后当我想重新连接时,我再次调用 ConnectGatt(),这给了我一个新的 BluetoothGatt 对象:

Gatt2 = Device.ConnectGatt (Android.App.Application.Context, false, GattCallback);

所以一旦我调用了 Gatt1.Disconnect(),我应该扔掉 Gatt1 吗?它不再有用了,因为当我重新连接时,我得到了一个新的 BluetoothGatt 对象?我是否需要调用一些函数来告诉 API 我不再使用 Gatt1?

(不,我实际上不会有两个变量,Gatt1 和 Gatt2,我只是使用这些名称来表示发生了两个不同的对象)

当我最终决定完全使用此 BLE 设备时,我不打算重新连接,然后我需要调用 Gatt.Close()(对吗?)

所以也许代码看起来更像这样?

BluetoothDevice Device = stuff();
BluetoothGatt Gatt = null;

if (connecting)
   Gatt = Device.ConnectGatt(...);
else if (disconnecting temporarily)
   Gatt.Disconnect();
else if (reconnecting after a temporary disconnection)
{
   Gatt = null;   // Yes?  Do I need to specifically Dispose() this previous object?
   Gatt = Device.ConnectGatt(...);
}
else if (disconnecting permanently)
{
   Gatt.Close();
   Gatt = null;
}

(再次,不,我不会写这样的函数,只是为了说明各种 BluetoothGatt 对象的寿命)

【问题讨论】:

  • 请问,如果一次连接到一个设备,为什么需要两个 gatt 对象?
  • 我没有。最初我没有看到 BluetoothGatt.Connect() 函数,所以我认为我必须第二次调用 BluetoothDevice.ConnectGatt() - 生成第二个 BluetoothGatt 对象。我现在认为这没有必要。

标签: android bluetooth bluetooth-lowenergy android-bluetooth


【解决方案1】:

您还需要在使用完第一个 BluetoothGatt 对象 (Gatt1) 后对其进行处理,方法是调用它的 close() 方法。我猜只留下垃圾收集来清理它不会起作用,因为它没有调用内部蓝牙堆栈来清理它的终结器。如果您不关闭对象而只是删除引用,您最终会用完 BluetoothGatt 对象(设备上所有应用程序总共最多可以有 32 个)。

【讨论】:

    【解决方案2】:
    Gatt1 = Device.ConnectGatt (Android.App.Application.Context, false, GattCallback);
    

    后面应该是:

    Gatt1.connect(); 
    

    Gatt1.disconnect() 对于您的目的是正确的。重新连接时,不需要 Gatt1 = null。只需再次调用 device.connectGatt() 和 Gatt1.connect() 即可。完成后:

    if(Gatt1!=null) {
         Gatt1.disconnect();
         Gatt1.close();
    }
    

    【讨论】:

    • 在我的测试中,我不需要 both ConnectGatt() 和 connect()。
    • @BettyCrokker 啊,是的,我的错。 Connect() 应该在重新连接后使用。
    【解决方案3】:

    在阅读了这些建议并进行了更多研究之后,我认为答案是这样的:

    BluetoothDevice Device = stuff();
    BluetoothGatt Gatt = null;
    
    if (connecting)
       Gatt = Device.ConnectGatt(...);
    else if (disconnecting temporarily)
       Gatt.Disconnect();
    else if (reconnecting after a temporary disconnection)
       Gatt.Connect();
    else if (disconnecting permanently)
    {
       Gatt.Disconnect();
       Gatt.Close();
       Gatt = null;
    }
    

    使用一堆额外的代码来等待连接/断开连接操作完成。

    【讨论】:

      猜你喜欢
      • 2014-05-05
      • 1970-01-01
      • 2016-06-14
      • 2012-10-17
      • 1970-01-01
      • 1970-01-01
      • 2015-12-18
      • 2021-10-27
      • 2013-11-17
      相关资源
      最近更新 更多