Android BLE (Bluetooth Low Energy) Connect/Disconnect/Reconnect

Viewed 3816

The Android BLE API seems odd, maybe I'm missing something. What I need to do, is to make a connection to a BLE device, then if things are idle for a while disconnect temporarily, but when the user wants to do something new I want to reconnect.

To connect initially, I call:

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

Then I'm thinking to do my temporary disconnect I call

Gatt1.Disconnect();

And then when I want to re-connect, I call ConnectGatt() again, which gives me a new BluetoothGatt object:

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

So once I've called Gatt1.Disconnect(), I should just throw away Gatt1? It's not useful anymore, since when I re-connect I get a new BluetoothGatt object? Do I need to call some function to tell the API that I'm not using Gatt1 anymore?

(no, I wouldn't actually have two variables, Gatt1 and Gatt2, I'm just using those names to indicate there are two different objects happening)

When I eventually decided I'm completely done with this BLE device, I'm not planning on ever re-connecting, then I need to call Gatt.Close() (right?)

So maybe the code looks more like this?

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

(again, no, I wouldn't write such a function, it's just to illustrate the lifespan of the various BluetoothGatt objects)

3 Answers
Related