Search code examples
androidbluetoothbluetooth-lowenergygattandroid-6.0.1-marshmallow

Android BLE: onCharacteristicRead works only first time


Gatt communication works only first time it is used.
I have read a lot of issues related to this one but no solution helped.
Whole process:
1. Restart phone
2. Run the app
3. App connects to BLE device and fetches list of accessible Wifi networks (SdkGattAttributes.WIFI_CHAR_WIFI_LIST)
till now everything ok
4. restart app
5. App connects to device and tries to fetch wifi list but onCharacteristicRead is never received. No writeCharacteristic was sent prio this
6. After phone restart app is able to fetch wifi list but again only once
What can be wrong. Some resources freeing or what? I can post some code If needed.
Thanks in advance.


Solution

  • I found the solution in the end so I post it here for others.

    Problem was that after successful connection MTU was set mBluetoothGatt.requestMtu(512) and services were requested mBluetoothGatt.discoverServices() one after another which probably confused gatt.

    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        if (newState == BluetoothProfile.STATE_CONNECTED) {
            mBluetoothGatt.discoverServices();
            mBluetoothGatt.requestMtu(512);
        }
    }
    

    Solution: first request mtu and when finshed discover services

    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        if (newState == BluetoothProfile.STATE_CONNECTED) {
            mBluetoothGatt.requestMtu(512);
        }
    }
    public void onMtuChanged (BluetoothGatt gatt, int mtu, int status) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            mBluetoothGatt.discoverServices();
        }
    }