最近做android BLE開發,由於有人把大致框架搭建好了(其實也就是SDK裏的samples中的東西),藍牙的流程也很快就熟悉了。然後馬上也就遇到了問題。
其實問題歸結起來就一個:BLE斷開後,重連不穩定,有可能還會連不上。
從logcat上看到的錯誤主要有這麼幾條:
L2CAP - LE - cannot start new connection at conn st : 2
L2CAP - LE - cannot start new connection at conn st : 3
onClientConnectionState() - status = 133 clientIf = 5 device = xxxxxxxxxxxx;
當然還有很多人遇到的status = 129,這個我倒是沒碰到。
先說解決問題的首要條件吧:android 4.4.3以上的系統。
因爲之前碰到的問題都是在android4.4.2上遇到的,經過一些調試,改善了一些情況,但偶爾連不上的問題還是解決不了。google上看了前輩們提的問題,決定升級系統,然後,就來這裏和大家分享經驗啦!
附上google上關於這個問題的一個鏈接吧,有用的信息還是很多的:https://code.google.com/p/android/issues/detail?id=58381
關於L2CAP的問題,找到了一些資料,就一起貼在這裏了:
L2CAP BLE Connection status (st) value : Following are the values of st (status) which is BLE Connection status that l2cap returns while showing an error: #define BLE_CONN_IDLE 0 #define BLE_DIR_CONN 1 #define BLE_BG_CONN 2 #define BLE_CONN_CANCEL 3 Source# http://androidxref.com/4.4_r1/xref/external/bluetooth/bluedroid/stack/btm/btm_ble_int.h#189
這些也都是來自上面那個google的鏈接裏的。
針對BLE斷開重連,速度比較慢的情況,我的處理方法是,在每次connect之前,都BlueToothGatt.close();這樣就能保證每次都是新連接,而不是重連。建立新連接的速度還是很快的。當然,我比較奇葩的在connect之前close,把close放在disconnect之後也是可以的。
有什麼不對的地方,歡迎拍磚~