Android BLE扫描无法找到设备 [英] Android BLE Scan never finds devices

查看:121
本文介绍了Android BLE扫描无法找到设备的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几天以来,我尝试在我的APP中实现BLE连接.我知道我尝试连接的设备功能齐全,所以问题一定出在我的代码上.

Since a few days I try to implement an BLE connection in my APP. I know that the Device, I try to connect with, is full functional, so the problem must be my code.

我使用 BluetoothLeScanner.startScan()方法.
但是永远不会调用回调方法.

I use the BluetoothLeScanner.startScan() method.
But the callback Method is never called.

   public void startScan() {
        if (bluetoothAdapter != null && bluetoothAdapter.isEnabled()) {
            isScanning = true;
            Handler mHandler = new Handler();
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mainActivityHandler.setMSG("Scan stopped");
                    isScanning = false;
                    leScanner.stopScan(scanCallback);
                }
            }, SCAN_TIME);

            mainActivityHandler.setMSG("Start scan");

            try {

                leScanner.startScan(scanCallback);
            } catch (Exception e) {
                mainActivityHandler.catchError(e);
            }

        } else mainActivityHandler.catchError(new Exception("Bluetooth not activated"));
    }

我的CallbackMethod(不知道我是否正确使用了gatt,但这是另一个问题):

My CallbackMethod (dont know if I use gatt correctly, but this is a other question):

    private ScanCallback scanCallback = new ScanCallback() {


    @Override
    public void onBatchScanResults(List<ScanResult> results) {
        mainActivityHandler.setMSG("Callback");
        isScanning = false;
        try {

            mainActivityHandler.setMSG("Connected to " + results.get(0).getDevice().getName());
            gatt = results.get(0).getDevice().connectGatt(mainActivity, true, bluetoothGattCallback);

            BluetoothGattDescriptor descriptor;
            for (int i = 0; i < charIDs.length; i++) {
                gatt.setCharacteristicNotification(gatt.getService(serviceID[0]).getCharacteristic(charIDs[i]), true);

                descriptor = gatt.getService(serviceID[0]).getCharacteristic(charIDs[0]).getDescriptor(charIDs[i]);
                descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                gatt.writeDescriptor(descriptor);
            }
        } catch (Exception e) {
            mainActivityHandler.catchError(e);
        }

    }
};

推荐答案

问题

问题是您只覆盖了 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();

这篇关于Android BLE扫描无法找到设备的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆