@SuppressLint("MissingPermission") // We check before this is called
        @Override
        public void onConnectionStateChange(final BluetoothGatt gatt,
                                            final int status,
                                            final int newState) {

            Log.d(TAG, "onConnectionStateChange: status=" + status + ", newState=" + newState);

            if (newState == BluetoothProfile.STATE_CONNECTED) {
                setConnectionState(State.CONNECTED, true);
                Log.i(TAG, "Connected to GATT server.");
                // Attempts to discover services after successful connection.
                Log.i(TAG, "Attempting to start service discovery:" + mBluetoothGatt.discoverServices());

            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                // Make sure we tidy up. On certain devices reusing a Gatt after a disconnection
                // can cause problems.
                disconnect();

                setConnectionState(State.DISCONNECTED, true);
                Log.i(TAG, "Disconnected from GATT server.");
            }
        }
Service for managing connection and data communication with a GATT server hosted on a
given Bluetooth LE device.
sample_app/src/main/java/uk/co/alt236/btlescan/services/BluetoothLeService.java