capacitor-community / bluetooth-le

Capacitor plugin for Bluetooth Low Energy
MIT License
281 stars 85 forks source link

fix: add checking bluetooth for disconnect in Device.kt #648

Closed corentin35000 closed 6 months ago

corentin35000 commented 6 months ago

In the old version, if Bluetooth was disabled during or just before the disconnect attempt, your application would still attempt to disconnect, which would likely result in a timeout or other form of error because the operation could not be completed. completed.

With the new code, this is what happens:

Checking Bluetooth status: Before attempting any disconnect operation, the code checks whether Bluetooth is enabled on the device (bluetoothAdapter.isEnabled). This step is crucial because it prevents the attempt to disconnect if Bluetooth is disabled, thus avoiding unnecessary wait time and timeout error. Immediate error handling: If Bluetooth is turned off, the code immediately resolves the callback with a specific error ("Failed: Bluetooth is turned off."). This allows your application to handle this specific state appropriately, for example by informing the user that Bluetooth must be enabled to disconnect. Reduction of timeout errors: By not disconnecting when Bluetooth is disabled, you avoid encountering a timeout due to an attempt to disconnect on a BluetoothGatt that is not operational or does not exist, because the Bluetooth disconnection has deactivated or invalidated the bluetoothGatt instance.

Why the code works better now: Immediate Bluetooth status response: The code immediately provides a Bluetooth status response, which is a significant improvement in user experience and control logic. Instead of letting the user wait for the timeout to end to discover that the operation cannot be completed, they receive an instant response. Explicit control of error flows: By explicitly handling the case where Bluetooth is disabled, you have better control over error flows in your application, allowing these situations to be handled in a more predictable and structured way. Reconnecting after reactivation: As the code prevents unnecessary operation when Bluetooth is disabled, it minimizes conflicting or problematic interactions with BluetoothGatt. This can contribute to a more stable environment for later reconnection once Bluetooth is re-enabled. This type of proactive device state management is essential in the development of mobile applications involving Bluetooth communications, improving the robustness and responsiveness of the application.

I had strange behavior especially on Android 11 and 12, since this fix I no longer have any problems!