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

问题描述:

Android BLE API看起来很奇怪,也许我错过了一些东西。我需要做的是建立一个BLE设备的连接,如果事情暂时闲置一段时间,但当用户想要做一些新的事情时,我想重新连接。Android 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对象的生存期)

+0

请问如果您一次连接到一台设备,为什么需要两个gatt对象? – Avinash4551

+0

我不知道。最初我没有看到BluetoothGatt.Connect()函数,所以我想我必须再次调用BluetoothDevice.ConnectGatt() - 生成第二个BluetoothGatt对象。我现在看到这不是必要的。 –

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

在我的测试中,我不需要_both_ ConnectGatt()和connect()。 –

+0

@BettyCrokker是的,我的坏。 Connect()应该在重新连接后使用。 –

您还需要配置第1 BluetoothGatt对象(Gatt1),当你用它做,通过调用它的close()方法。只是离开垃圾收集来清理它将而不是工作我猜想,因为它没有终结者调用内部蓝牙堆栈来清理它。如果您不关闭对象并放弃参考,则最终将耗尽BluetoothGatt对象(设备上可以共有最多32个用于所有应用程序的对象)。

阅读这些建议,并做一些更多的研究后,我想答案是这样的:

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

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