I am developing an app in which I can both find and configure BLE devices. I am using standard Android BLE API, but recently I've encountered some strange problems.
When I turn on my app the BLE scan works OK. I am scanning using:
mBluetoothAdapter.startLeScan(mLeScanCallback); // for Kitkat and below
and
mBluetoothAdapter.getBluetoothLeScanner().startScan(mScanCallback); // for Lollipop and above
In the Logcat I am getting following messages (I guess this is important for this issue):
D/BluetoothAdapter: onClientRegistered() - status=0 clientIf=5
In my app I can also read certain characteristics from my BLE devices (eg. battery state). I connect to a device to read this characteristic in a separate fragment using:
mBluetoothManager = (BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = mBluetoothManager.getAdapter();
mBluetoothDevice = mBluetoothAdapter.getRemoteDevice(mMacAddress);
mBluetoothGatt = mBluetoothDevice.connectGatt(mContext, false, mGattCallback);
The characteristics are read correctly. In the onCharacteristicRead callback I also disconnect and close Gatt:
mBluetoothGatt.disconnect();
mBluetoothGatt.close();
Each time I open a fragment to read a characteristic (no matter whether it is the same device or not) clientIf value increases. I can see in the LogCat:
D/BluetoothGatt: onClientRegistered() - status=0 clientIf=6
D/BluetoothGatt: onClientRegistered() - status=0 clientIf=7
D/BluetoothGatt: onClientRegistered() - status=0 clientIf=8
D/BluetoothGatt: onClientRegistered() - status=0 clientIf=9
D/BluetoothGatt: onClientRegistered() - status=0 clientIf=10
Everything works fine until the clientIf value equals 10. BLE scan stops finding any devices, I can't connect to any of my devices to read any characteristics etc. And the LogCat infinitely displays these messages:
D/BluetoothGatt: unregisterApp() - mClientIf=0
D/BluetoothGatt: onClientRegistered() - status=133 clientIf=0
The only way to fix it is to kill the app and relaunch it or restart Bluetooth by turning it off and on manually. I've encountered this issue only on certain devices such as Xperia Z1 (Android KitKat) and Galaxy S4 (Android Lollipop). I couldn't reproduce this issue on Xperia Z3 Compact running Android Marshmallow...
Is there anything I can do about it? I've already tried multiple "solutions" such as - calling all BLE methods from the UI thread and closing/disconnecting GATT, but nothing helps. How can I fix it?