yanshouwang / bluetooth_low_energy

A Flutter plugin for controlling the bluetooth low energy.
https://pub.dev/packages/bluetooth_low_energy
MIT License
51 stars 17 forks source link

MyCentralManager is not using TRANSPORT_LE when connecting from Android 5 #110

Open ekuleshov opened 3 days ago

ekuleshov commented 3 days ago

Bluetooth Module

Amazon Fire7 gen5 2015

What is your problem?

MyCentralManager is using a default BT transport (LE + 2.0) when Android platform is below 23 (e.g. Android 5)

https://github.com/yanshouwang/bluetooth_low_energy/blob/master/bluetooth_low_energy_android/android/src/main/kotlin/dev/hebei/bluetooth_low_energy_android/MyCentralManager.kt#L173-L178

That often leads to 133 issues if peripheral device supports both 2.0 and BLE link. I see a lot of that on some old Amazon Fire 7 devices running Android 5 and issue can't be worked around in the current version of the bluetooth_low_energy plugin.

To get around that pretty much all native Android BLE helper libraries are using reflection to call a hidden private method on BluetoothDevice class:

https://github.com/douglasjunior/AndroidBluetoothLibrary/blob/master/BluetoothLowEnergyLibrary/src/main/java/com/github/douglasjunior/bluetoothlowenergylibrary/BluetoothLeService.java#L317-L330

            // fall back to reflection for Android 5 to force TRANSPORT_LE
            try {
                Method method = device.getClass().getDeclaredMethod("connectGatt",
                        Context.class, Boolean.TYPE, BluetoothGattCallback.class, Integer.TYPE);
                method.setAccessible(true);
                btGatt = (BluetoothGatt) method.invoke(device, this, false, gattCallback, 2 /* BluetoothDevice.TRANSPORT_LE */);
            } catch (Exception ex) {
                btGatt = device.connectGatt(this, false, gattCallback);
            }
yanshouwang commented 20 hours ago

I don't know about this reflect method before, it's hard to find a Android 5 device for test.

I'm a little busy on another project these days. I'm happy to merge this fix if you can make a PR.