diff --git a/packages/flutter_blue_plus_android/android/src/main/java/com/lib/flutter_blue_plus/FlutterBluePlusPlugin.java b/packages/flutter_blue_plus_android/android/src/main/java/com/lib/flutter_blue_plus/FlutterBluePlusPlugin.java index 2e9d7814..0e624c92 100644 --- a/packages/flutter_blue_plus_android/android/src/main/java/com/lib/flutter_blue_plus/FlutterBluePlusPlugin.java +++ b/packages/flutter_blue_plus_android/android/src/main/java/com/lib/flutter_blue_plus/FlutterBluePlusPlugin.java @@ -230,7 +230,7 @@ public class FlutterBluePlusPlugin implements } } - disconnectAllDevices("onDetachedFromEngine"); + disconnectAllDevices("onDetachedFromEngine", false); context.unregisterReceiver(mBluetoothBondStateReceiver); context.unregisterReceiver(mBluetoothPairRequestReceiver); @@ -338,7 +338,8 @@ public class FlutterBluePlusPlugin implements // all dart state is reset after flutter restart // (i.e. Hot Restart) so also reset native state - disconnectAllDevices("flutterRestart"); + // #794: onMethodCall already holds mMethodCallMutex. + disconnectAllDevices("flutterRestart", true); log(LogLevel.DEBUG, "connectedPeripherals: " + mConnectedDevices.size()); @@ -1825,51 +1826,67 @@ public class FlutterBluePlusPlugin implements } } - private void disconnectAllDevices(String func) + // #794: this method mutates the connection maps and must be serialized + // against the GATT callbacks, which take mMethodCallMutex. A caller that + // already holds the (non-reentrant) mutex passes callerHoldsMutex=true: + // flutterRestart runs inside onMethodCall, which holds it, and acquiring + // again there would deadlock Hot Restart. + private void disconnectAllDevices(String func, boolean callerHoldsMutex) { - log(LogLevel.DEBUG, "disconnectAllDevices("+func+")"); + if (!callerHoldsMutex) { + acquireMutex(mMethodCallMutex); + } + try { + log(LogLevel.DEBUG, "disconnectAllDevices("+func+")"); - // merge connected & autoconnected - Map allDevices = new HashMap<>(); - allDevices.putAll(mConnectedDevices); - allDevices.putAll(mAutoConnected); + // merge connected & autoconnected + Map allDevices = new HashMap<>(); + allDevices.putAll(mConnectedDevices); + allDevices.putAll(mAutoConnected); - // request disconnections - for (BluetoothGatt gatt : allDevices.values()) { + // request disconnections + for (BluetoothGatt gatt : allDevices.values()) { - if (func == "adapterTurnOff") { + if (func == "adapterTurnOff") { - // Note: - // - calling `disconnect` and `close` after the adapter - // is turned off is not necessary. It is implied. - // Calling them leads to a `DeadObjectException`. - // - But, we must make sure the disconnect callback is called. - // It's surprising but android does not invoke this callback itself. - mGattCallback.onConnectionStateChange(gatt, 0, BluetoothProfile.STATE_DISCONNECTED); + // Note: + // - calling `disconnect` and `close` after the adapter + // is turned off is not necessary. It is implied. + // Calling them leads to a `DeadObjectException`. + // - But, we must make sure the disconnect callback is called. + // It's surprising but android does not invoke this callback itself. + // #794: call the locked core directly; the public callback + // would try to re-acquire the mutex this method holds. + handleConnectionStateChangeLocked(gatt, 0, BluetoothProfile.STATE_DISCONNECTED); - } else { + } else { - String remoteId = gatt.getDevice().getAddress(); + String remoteId = gatt.getDevice().getAddress(); - // disconnect - log(LogLevel.DEBUG, "calling disconnect: " + remoteId); - gatt.disconnect(); + // disconnect + log(LogLevel.DEBUG, "calling disconnect: " + remoteId); + gatt.disconnect(); - // it is important to close after disconnection, otherwise we will - // quickly run out of bluetooth resources, preventing new connections - log(LogLevel.DEBUG, "calling close: " + remoteId); - gatt.close(); + // it is important to close after disconnection, otherwise we will + // quickly run out of bluetooth resources, preventing new connections + log(LogLevel.DEBUG, "calling close: " + remoteId); + gatt.close(); + } } - } - mConnectedDevices.clear(); - mCurrentlyConnectingDevices.clear(); - mBondingDevices.clear(); - mBondingPins.clear(); - mMtu.clear(); - mWriteChr.clear(); - mWriteDesc.clear(); - mAutoConnected.clear(); + mConnectedDevices.clear(); + mCurrentlyConnectingDevices.clear(); + mBondingDevices.clear(); + mBondingPins.clear(); + mMtu.clear(); + mWriteChr.clear(); + mWriteDesc.clear(); + mAutoConnected.clear(); + } finally { + if (!callerHoldsMutex) { + mMethodCallMutex.release(); + } + } } int getAppearanceFromScanRecord(ScanRecord adv) { @@ -2017,7 +2034,7 @@ public class FlutterBluePlusPlugin implements // disconnect all devices if (adapterState == BluetoothAdapter.STATE_TURNING_OFF || adapterState == BluetoothAdapter.STATE_OFF) { - disconnectAllDevices("adapterTurnOff"); + disconnectAllDevices("adapterTurnOff", false); } } }; @@ -2224,16 +2241,13 @@ public class FlutterBluePlusPlugin implements // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ // ██████ ██ ██ ███████ ███████ ██████ ██ ██ ██████ ██ ██ - private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() + // #794: the locked core of onConnectionStateChange. Callers MUST hold + // mMethodCallMutex: the public callback acquires it, and + // disconnectAllDevices, which already holds it, calls this directly + // (going through the public callback from there would deadlock on the + // non-reentrant Semaphore). + private void handleConnectionStateChangeLocked(BluetoothGatt gatt, int status, int newState) { - @Override - public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) - { - try { - // Prevent callback thread & method call thread from writing to - // mConnectedDevices & mCurrentlyConnectingDevices concurrently. - acquireMutex(mMethodCallMutex); - log(LogLevel.DEBUG, "onConnectionStateChange:" + connectionStateString(newState)); log(LogLevel.DEBUG, " status: " + hciStatusString(status)); @@ -2307,16 +2321,15 @@ public class FlutterBluePlusPlugin implements response.put("disconnect_reason_string", hciStatusString(status)); invokeMethodUIThread("OnConnectionStateChanged", response); - } finally { - mMethodCallMutex.release(); - } - } + } - // Android has an annoying edge case. If disconnect is called right as the connection is being - // established, Android sometimes ignores the request to disconnect and completes the connection - // anyway. To handle this case, we make sure the device is still in our currently connecting - // devices map, otherwise kill the connection since the user was not expecting it to connect. - private boolean handleUnexpectedConnectionEvents(BluetoothGatt gatt, int newState, String remoteId) + // Android has an annoying edge case. If disconnect is called right as the connection is being + // established, Android sometimes ignores the request to disconnect and completes the connection + // anyway. To handle this case, we make sure the device is still in our currently connecting + // devices map, otherwise kill the connection since the user was not expecting it to connect. + // (Hoisted out of the anonymous callback so handleConnectionStateChangeLocked can live at + // class level, #794.) + private boolean handleUnexpectedConnectionEvents(BluetoothGatt gatt, int newState, String remoteId) { boolean unexpectedEvent = false; if (newState == BluetoothProfile.STATE_CONNECTED) { @@ -2364,6 +2377,21 @@ public class FlutterBluePlusPlugin implements return unexpectedEvent; } + private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() + { + @Override + public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) + { + try { + // Prevent callback thread & method call thread from writing to + // mConnectedDevices & mCurrentlyConnectingDevices concurrently. + acquireMutex(mMethodCallMutex); + handleConnectionStateChangeLocked(gatt, status, newState); + } finally { + mMethodCallMutex.release(); + } + } + @Override public void onServicesDiscovered(BluetoothGatt gatt, int status) { diff --git a/packages/flutter_blue_plus_android/pubspec.yaml b/packages/flutter_blue_plus_android/pubspec.yaml index 570615b4..3cb4c5f6 100644 --- a/packages/flutter_blue_plus_android/pubspec.yaml +++ b/packages/flutter_blue_plus_android/pubspec.yaml @@ -1,6 +1,6 @@ name: flutter_blue_plus_android description: Android implementation of the flutter_blue_plus plugin. -version: 8.2.2+offband.1 +version: 8.2.2+offband.2 homepage: https://github.com/chipweinberger/flutter_blue_plus environment: