From 8a7de1584133ab00200553c29fca0efb3b243ce2 Mon Sep 17 00:00:00 2001 From: MrYoranimo Date: Sun, 21 Jan 2024 01:56:34 +0100 Subject: [PATCH] BtLEQueue: update device state on main looper If the device connection state is updated from two threads simultaneously (as in, from the main looper and from the thread that handles BluetoothDevice.connectGatt), a second update may get overridden by the first update if the broadcasts are handled out-of-order by the LocalBroadcastManager. By updating the device state through a handler on the main looper, the broadcasts are sent in order as they are processed from the looper's queue. This may be a potential solve for issue #3524. --- .../gadgetbridge/service/btle/BtLEQueue.java | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/nodomain/freeyourgadget/gadgetbridge/service/btle/BtLEQueue.java b/app/src/main/java/nodomain/freeyourgadget/gadgetbridge/service/btle/BtLEQueue.java index fceb6ab82..83bdb5695 100644 --- a/app/src/main/java/nodomain/freeyourgadget/gadgetbridge/service/btle/BtLEQueue.java +++ b/app/src/main/java/nodomain/freeyourgadget/gadgetbridge/service/btle/BtLEQueue.java @@ -227,7 +227,12 @@ public final class BtLEQueue { } protected boolean isConnected() { - return mGbDevice.isConnected(); + if (mGbDevice.isConnected()) { + return true; + } + + LOG.debug("isConnected(): current state = {}", mGbDevice.getState()); + return false; } /** @@ -285,11 +290,12 @@ public final class BtLEQueue { return result; } - private void setDeviceConnectionState(State newState) { - LOG.debug("new device connection state: " + newState); - - mGbDevice.setState(newState); - mGbDevice.sendDeviceUpdateIntent(mContext, GBDevice.DeviceUpdateSubject.CONNECTION_STATE); + private void setDeviceConnectionState(final State newState) { + new Handler(Looper.getMainLooper()).post(() -> { + LOG.debug("new device connection state: " + newState); + mGbDevice.setState(newState); + mGbDevice.sendDeviceUpdateIntent(mContext, GBDevice.DeviceUpdateSubject.CONNECTION_STATE); + }); } public void disconnect() {