BLE-如果“扫描”未找到任何内容,为什么没有回叫?

时间:2018-12-01 16:30:37

标签: android callback bluetooth-lowenergy

在我的应用中,我希望看门狗如此频繁地唤醒,并检查我们是否已连接到设备。我还希望用户现在可以按一个按钮进行连接。检查我们是否已经连接并取消请求很简单。但是,如果当前正在进行扫描,我也不想开始扫描。因此,我有一种方法可以像这样开始扫描:

void scanLeDevice(final boolean enable) {
    if (enable) {
        //Will stop the scanner in given amount of milliseconds
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mLEScanner.stopScan(mScanCallback);
            }
        }, SCAN_PERIOD);

        mLEScanner.startScan(filters, settings, mScanCallback);
        isScanning = true;
        Log.i("BLE_Service_Comm", "Scanning...");
    } else {
        mLEScanner.stopScan(mScanCallback);
        Log.i("BLE_Service_Comm", "Scanning stopped");
    }
}

请注意,我将“ isScanning”设置为true。如果收到任何回调,请确保将“ isScanning”设置为false:

private ScanCallback mScanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            isScanning = false;
            Log.i("BLE_Service_Comm", "Scan callback type " + String.valueOf(callbackType));
            Log.i("BLE_Service_Comm", "Scan callback " + result.toString());
            BluetoothDevice btDevice = result.getDevice();
            Log.i("BLE_Service_Comm", "Scan callback address " + btDevice.getAddress());
            connectToDevice(btDevice);
        }

        //Honestly don't know when it would return a "batch" like this
        @Override
        public void onBatchScanResults(List<ScanResult> results) {
            isScanning = false;
            Log.i("BLE_Service_Comm", "Batch results");
            for (ScanResult sr : results) {
                Log.i("BLE_Service_Comm", sr.toString());
            }
        }

        @Override
        public void onScanFailed(int errorCode) {
            isScanning = false;
            Log.e("BLE_Service_Comm", "Scan failed with Error Code: " + errorCode);
        }
    };

连接后,我可以找到所需的GATT配置文件,并且一切正常。当我的自动计时器唤醒或用户按下“连接”并且设备已连接或“ isScanning”为true时,它将忽略该请求。

但是,如果我的扫描没有找到设备,则mScanCallback永远不会运行,并且“ isScanning”将永久保持为真。在这种情况下,计时器醒来,或者用户按下“连接”将什么都不做,因为我会看到“ isScanning”为真。

我在这里错过了什么吗?有没有办法让ScanCallback告诉您扫描已完成并且什么都没找到?我的postDelayed Runnable方法在SCAN_PERIOD时间弄乱了任何内容后结束了扫描吗?

1 个答案:

答案 0 :(得分:0)

原来,我只需要在PostDelayed Runnable中将“ isScanning”设置为false。