且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Android BLE扫描无法找到设备

更新时间:2021-11-17 22:53:44

问题

问题是您只覆盖了 onBatchScanResults 方法,而不是 onScanResult 方法. onBatchScanResults 仅在以下情况下会被触发:

The Problem

The problem is that you are only overriding the onBatchScanResults method and not onScanResult method. onBatchScanResults will only get triggered if:

  1. 您已使用 ScanSettings.Builder ScanSettings 模式设置为 ScanSettings.SCAN_MODE_LOW_POWER (这是默认设置).
  2. 您已使用 ScanSettings.Builder 中的 setReportDelay(long reportDelayMillis)将报告延迟时间设置为大于0的某个值.
  1. You have set the ScanSettings mode to ScanSettings.SCAN_MODE_LOW_POWER (this is the default) using the ScanSettings.Builder.
  2. You have set the report delay time to some value >0 using setReportDelay(long reportDelayMillis) in your ScanSettings.Builder.

reportDelayMillis -报告延迟(以毫秒为单位).设置为0可立即通知结果.值> 0会使扫描结果排队,并在请求的延迟后或内部缓冲区填满时传递.

reportDelayMillis - Delay of report in milliseconds. Set to 0 to be notified of results immediately. Values > 0 causes the scan results to be queued up and delivered after the requested delay or when the internal buffers fill up.

例如:

public void startScan(BluetoothLeScanner scanner) {
    ScanFilter filter = new ScanFilter.Builder().setDeviceName(null).build();

    ArrayList<ScanFilter> filters = new ArrayList<ScanFilter>();
                    filters.add(filter);

    ScanSettings settings = new ScanSettings.Builder()
                                .setScanMode(ScanSettings.SCAN_MODE_LOW_POWER)
                                .setReportDelay(1l)
                                .build();

    Log.i(TAG,"The setting are "+settings.getReportDelayMillis());
    scanner.startScan(filters,settings,BLEScan);
}

解决方案

但是,您可能只想一次获得一次结果,而不是一批结果.为此,您无需修改​​ScanSettings,只需在 ScanCallback 中覆盖 onScanResult 方法即可.

private ScanCallback mScanCallback =
        new ScanCallback() {

    public void onScanResult(int callbackType, ScanResult result) {
        System.out.println(result.getDevice().getName())
        // Do whatever you want
    };

    ...
};

替代-RxAndroidBle

无论如何,我强烈建议您使用库 RxAndroidBle .它的维护非常好,可以立即解决许多BLE问题(扫描可能是BLE中不太复杂的部分).

The Alternative - RxAndroidBle

Anyway, I highly recommend using the library RxAndroidBle. It is very well maintained and it solves many of the BLE issues out of the box (scanning is maybe the less complicated part in BLE).

使用该库,可以像这样进行扫描:

Using that library, the scanning can be done like this:

Disposable scanSubscription = rxBleClient.scanBleDevices(


    new ScanSettings.Builder()
            // .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY) // change if needed
            // .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES) // change if needed
            .build()
        // add filters if needed
)
    .subscribe(
        scanResult -> {
            // Process scan result here.
        },
        throwable -> {
            // Handle an error here.
        }
    );

// When done, just dispose.
scanSubscription.dispose();