【发布时间】: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