@@ -90,6 +90,7 @@ public class BluetoothPeripheralManager {
9090 private @ NotNull final BluetoothLeAdvertiser bluetoothLeAdvertiser ;
9191 private @ NotNull final BluetoothGattServer bluetoothGattServer ;
9292 private @ NotNull final BluetoothPeripheralManagerCallback callback ;
93+ private @ Nullable BluetoothCentralManager centralManager = null ;
9394 protected @ NotNull final Queue <Runnable > commandQueue = new ConcurrentLinkedQueue <>();
9495 private @ NotNull final HashMap <BluetoothGattCharacteristic , byte []> writeLongCharacteristicTemporaryBytes = new HashMap <>();
9596 private @ NotNull final HashMap <BluetoothGattDescriptor , byte []> writeLongDescriptorTemporaryBytes = new HashMap <>();
@@ -106,6 +107,15 @@ public class BluetoothPeripheralManager {
106107 public void onConnectionStateChange (final BluetoothDevice device , final int status , final int newState ) {
107108 if (status == BluetoothGatt .GATT_SUCCESS ) {
108109 if (newState == BluetoothProfile .STATE_CONNECTED ) {
110+
111+ // First check if this is a connecting peripheral because Android
112+ // will also call this callback for connecting peripherals
113+ if (centralManager != null ) {
114+ if (centralManager .unconnectedPeripherals .containsKey (device .getAddress ())) {
115+ return ;
116+ }
117+ }
118+
109119 // Call connect() even though we are already connected
110120 // It basically tells Android we will really use this connection
111121 // If we don't do this, then cancelConnection won't work
@@ -119,7 +129,7 @@ public void onConnectionStateChange(final BluetoothDevice device, final int stat
119129
120130 handleDeviceConnected (device );
121131 } else if (newState == BluetoothProfile .STATE_DISCONNECTED ) {
122- // Deal is double disconnect messages
132+ // Deal with double disconnect messages
123133 if (!connectedCentralsMap .containsKey (device .getAddress ())) return ;
124134
125135 handleDeviceDisconnected (device );
@@ -486,6 +496,10 @@ public BluetoothPeripheralManager(@NotNull final Context context, @NotNull final
486496 context .registerReceiver (adapterStateReceiver , filter );
487497 }
488498
499+ public void setCentralManager (@ NotNull final BluetoothCentralManager central ) {
500+ this .centralManager = Objects .requireNonNull (central );
501+ }
502+
489503 /**
490504 * Close the BluetoothPeripheralManager
491505 *
0 commit comments