I am trying to establish a connection with a device that is turned on from time to time, transmits data and disconnects. I tried different options and it turned out with the following Callback:
protected static BluetoothGattCallback callback = new BluetoothGattCallback() { @Override public void onConnectionStateChange(final BluetoothGatt gatt, int status, int newState) { Log.d(TAG, String.format("BluetoothGattCallback: onConnectionStateChange: status:%d newState:%d", status, newState)); if (newState == BluetoothProfile.STATE_DISCONNECTED) { Log.d(TAG, "Disconnected from GATT server. Flag = " + connectionStateFlag); mainThreadHandler.postDelayed(new Runnable() { @Override public void run() { gatt.getDevice().connectGatt(applicationContext, true, callback); } }, 2000); return; } if (newState == BluetoothProfile.STATE_CONNECTED) { Log.d(TAG, "Connected to GATT server. Flag = " + connectionStateFlag); Log.i(TAG, "Connected to GATT server."); ... } } };`
It seems that everything works, but for some reason sometimes after 20 seconds after connecting to Gatt, the onConnectionStateChange with the Disconect state comes again. In this case, the client number in the line in the BluetoothGatt log: onClientRegistered () - status = 0 clientIf = 9 increases. Without this additional reconnection, this number is the same as the previous connection. And sometimes this reconnection is repeated several times, and sometimes it does not occur at all. And for some reason, suddenly, Bluetooth stops responding when the device is turned on, and you have to run the scan again to connect, and sometimes even restart Bluetooth itself. I do not understand what could be the matter? I tried on another phone on 4.4, sometimes everything works quite smoothly with no additional reconnections. But sometimes these reconnections happen every time. No system. What matters to me is to ensure that I do not get 2 gatt for one device at a time. And judging by the fact that I sometimes start getting 2 onCharactericsticChange for one request, it seems that this is exactly what happens. And I can not find any system in the behavior of the application. It does not depend on the phone, nor on the version of android. Everything works fine without any problems, then suddenly everything goes hand in hand because there are 2 answers for each request and the whole sequence of questions and answers gets lost.