Android 修改ble藍牙20字節限制

ble藍牙BluetoothGattCallback:onCharacteristicChanged接收數據時,被限制只能接收20字節(實際爲23字節,其中3字節爲ATT佔用),要突破20字節需要在BluetoothGattCallback:onConnectionStateChange連接成功時加入一下設置:

int mut = 512
bluetoothGatt.requestMtu(mut)

加入這個設置之後,會回調BluetoothGattCallback:onMtuChanged,在此可接收設置成功與否:

@Override
        public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
            super.onMtuChanged(gatt, mtu, status);
            if (BluetoothGatt.GATT_SUCCESS == status) {
                LogHelper.log("onMtuChanged success MTU = " + mtu);              
            } else {
                LogHelper.log("onMtuChanged fail ");
            }
        }

此時如果無法接收數據,則可能是因爲你在onConnectionStateChange中設置做了搜尋服務工作:bluetoothGatt.discoverServices() 如下:

 @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        
            if (status == BluetoothGatt.GATT_SUCCESS) {
                if (bluetoothGatt == null) {
                    return;
                }
                //設置接收數據長度,默認20
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                bluetoothGatt.requestMtu(32)//*********
                }
                bluetoothGatt.discoverServices(); //*********
                Log.e("state", "連接成功");
            } else if (newState == BluetoothGatt.STATE_DISCONNECTED) {
                // 斷開成功
                Log.e("state", "連接斷開");
 
            }
          
        }

只需要將bluetoothGatt.discoverServices()移到onMtuChanged中就能接收數據了,如下:

@Override
        public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
            super.onMtuChanged(gatt, mtu, status);
            if (BluetoothGatt.GATT_SUCCESS == status) {
                LogHelper.log("onMtuChanged success MTU = " + mtu);    
                bluetoothGatt.discoverServices();          
            } else {
                LogHelper.log("onMtuChanged fail ");
            }
        }

因爲BluetoothGatt對象的所有請求都必須是序列化的,還有其他待處理的請求時無法請求mtu。

《上一篇:Android連接ble藍牙

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章