【解决问题】FlutterBlue在安卓手机上无法连接蓝牙设备,扫描缓慢

现在的FlutterBlue在安卓手机上很难搜索连接,在iOS上是没问题的,进行下列更改可以快速修复这个问题,但是会损失掉一些功能,不能通过指定Service的UUID搜索到设备(因为uuids数组被改成了[])。

懒人可以直接用我fork之后修改的版本,修改YML文件的flutter_blue地址如下:

flutter_blue: 
    git: 
      url: git://github.com/mjl0602/flutter_blue.git

If you can’t use flutterblue connect device with Android Phone. You can try low version Api of Android. These apis are deprecated but worked very well in some Android Phone. These
Phones are bad support with new API: you can call the function successful, but scan and connect will be very slow and easy connect fail. To solve this problem, change file:
android/src/main/java/com/pauldemarco/flutterblue/

see new file on: https://github.com/mjl0602/fl...

This change didn't solve this problem completely. To solve this problem, must add new args to control the api version. but not use Build.VERSION.SDK_INT. It's works bad.

简单的说,就是很多手机系统到了新版本,但是对新版本的硬件API支持的很差,强制换成老版本的用法就好了。希望作者加一个字段来控制具体用什么版本的API来搜索。

  • Change connect way.
// old code,hardly connect device on Red Mi Note 4 
// BluetoothGatt gattServer = device.connectGatt(registrar.activity(), options.getAndroidAutoConnect(), mGattCallback);

// improve MI phone connect speed. If didn't call connect,Mi phone can't connect success
BluetoothGatt gattServer = device.connectGatt(registrar.activity(), false, mGattCallback);
gattServer.connect();
  • Use old version api
// use old version api
private void startScan(MethodCall call, Result result) {
    byte[] data = call.arguments();
    Protos.ScanSettings settings;
    try {
        settings = Protos.ScanSettings.newBuilder().mergeFrom(data).build();
        // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        //     startScan21(settings);
        // } else {
            startScan18(settings);
        // }
        result.success(null);
    } catch (Exception e) {
        result.error("startScan", e.getMessage(), e);
    }
}

private void stopScan() {
    // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    //     stopScan21();
    // } else {
        stopScan18();
    // }
}
  • Remove uuids arg.
// boolean success = mBluetoothAdapter.startLeScan(uuids, getScanCallback18());
boolean success = mBluetoothAdapter.startLeScan(getScanCallback18());

本文禁止任何类型转载

相关推荐