2017-08-07 932 views
1

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對象。我現在看到這不是必要的。 –

回答

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

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

+0

@BettyCrokker是的,我的壞。 Connect()應該在重新連接後使用。 –

0

您還需要配置第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; 
} 

與一堆額外的代碼來等待連接/斷開操作來完成。