其他分享
首页 > 其他分享> > Android 7.0 ble扫描没有结果

Android 7.0 ble扫描没有结果

作者:互联网

当我开始ble(蓝牙Le)扫描几秒钟,然后停止扫描.然后开始,然后停止……
大约5-8循环后,开始动作将无效,这意味着无法接收扫描记录.
1.此条件仅出现在Android 7.0或更高版本(7.1.1);
2.我尝试了两种扫描方法:BluetoothAdapter.startLeScan()和Scanner.startScan(),没有区别.

private void scanToggle(final boolean enable) {
    mScanHandler.removeCallbacks(scanTask);
    if (enable) {
        TelinkLog.i("ADV#scanner#startScan");
        scanner = mBluetoothAdapter.getBluetoothLeScanner();
        scanner.startScan(null, settings, scanCallback);
        mScanning = true;
        mDeviceList.clear();
        mListAdapter.notifyDataSetChanged();
       //mBluetoothAdapter.startLeScan(leScanCallback);
        mScanHandler.postDelayed(scanTask, SCAN_PERIOD);
    } else {
        TelinkLog.i("ADV#scanToggle#stopScan");
        mScanning = false;
        //mBluetoothAdapter.stopLeScan(leScanCallback);
        scanner.stopScan(scanCallback);
    }
    invalidateOptionsMenu();
}


private BluetoothAdapter.LeScanCallback leScanCallback = new BluetoothAdapter.LeScanCallback() {
    @Override
    public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
        TelinkLog.d("scan:" + device.getName());
        for (AdvDevice advDevice : mDeviceList) {
            if (device.getAddress().equals(advDevice.device.getAddress())) return;
        }
        mDeviceList.add(new AdvDevice(device, rssi, scanRecord));
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mListAdapter.notifyDataSetChanged();
            }
        });
    }
};

private ScanCallback scanCallback = new ScanCallback() {
    @Override
    public void onScanResult(int callbackType, ScanResult result) {
        super.onScanResult(callbackType, result);
        for (AdvDevice advDevice : mDeviceList) {
            if (result.getDevice().getAddress().equals(advDevice.device.getAddress())) return;
        }
        mDeviceList.add(new AdvDevice(result.getDevice(), result.getRssi(), result.getScanRecord().getBytes()));
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mListAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    public void onBatchScanResults(List<ScanResult> results) {
        super.onBatchScanResults(results);
    }

    @Override
    public void onScanFailed(int errorCode) {
        super.onScanFailed(errorCode);
    }
};

解决方法:

您可能会遇到Android 7中新的和未记录的行为更改,这些更改会阻止应用程序进行过于频繁的扫描.

我写了一篇关于它的博客文章:
https://blog.classycode.com/undocumented-android-7-ble-behavior-changes-d1a9bd87d983

标签:android-7-0-nougat,android,bluetooth-lowenergy
来源: https://codeday.me/bug/20190724/1523340.html