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

时间:2017-08-07 15:44:28

标签: android bluetooth bluetooth-lowenergy android-bluetooth

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对象的生命周期)

3 个答案:

答案 0 :(得分:1)

完成后,您还需要通过调用close()方法来处置第一个BluetoothGatt对象(Gatt1)。只是留下垃圾收集来清理它将工作我猜,因为它没有终结器调用内部蓝牙堆栈来清理它。如果你没有关闭对象而只是放弃引用,你最终将耗尽BluetoothGatt对象(设备上的所有应用程序最多可以共有32个。)

答案 1 :(得分: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();
}

答案 2 :(得分: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;
}

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