安卓蓝牙低功耗(BLE)连接/断开连接/重新连接

3

安卓蓝牙低功耗(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对象,所以Gatt1已经没有用了是吗?我需要调用某个函数告诉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对象的寿命)
注:BluetoothGatt是一种用于与蓝牙设备通信的API。

请问为什么在一次只连接一个设备的情况下需要两个Gatt对象? - Avinash4551
我一开始并没有看到BluetoothGatt.Connect()函数,所以我认为我必须再次调用BluetoothDevice.ConnectGatt()来生成第二个BluetoothGatt对象。现在我明白这是不必要的。 - Betty Crokker
3个回答

1

当你完成使用第一个BluetoothGatt对象(Gatt1)时,需要调用close()方法来处理它。仅仅依靠垃圾回收来清理它似乎行不通,因为它没有终结器来调用内部的蓝牙堆栈来清理它。如果你不关闭该对象,只是丢弃引用,最终将会耗尽BluetoothGatt对象(对于所有应用程序一共只能有32个)。


0

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

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

加入大量额外的代码以等待连接/断开操作完成。


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

1
在我的测试中,我不需要同时使用ConnectGatt()和connect()。 - Betty Crokker
@BettyCrokker 哦,是的,我的错。在重新连接后应该使用Connect()。 - Lillian H

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接