在Android 8.1.0中移动屏幕关闭时BLE扫描停止

时间:2018-01-05 13:27:52

标签: android bluetooth-lowenergy

我将此权限放在清单文件中。

<uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 

这是一种开始扫描方法。屏幕打开时工作正常。但是当屏幕关闭时,扫描停止并在屏幕再次打开时恢复。 我试过solution,但仍面临同样的问题。

 void startScan() {
            if (!mScanning) {
                final BluetoothLeScannerCompat scanner = BluetoothLeScannerCompat.getScanner();
                final ScanSettings settings = new ScanSettings.Builder()
                        .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).setReportDelay(0).setUseHardwareBatchingIfSupported(false).setUseHardwareFilteringIfSupported(false).build();

                ScanFilter.Builder builder = new ScanFilter.Builder();

               builder.setServiceUuid(new ParcelUuid(THINGY_BASE_UUID));
                ScanFilter filter = builder.build();

                final List<ScanFilter> filters = new ArrayList<>();
                filters.add(filter); // Add Filter using UUID
                scanner.startScan(filters, settings, scanCallback);
                mScanning = true;
            }
        }

这是获取扫描结果的回调方法。

 private ScanCallback scanCallback = new ScanCallback() {
        @Override
        public void onScanResult(final int callbackType, final ScanResult result) {
            // do nothing
            Log.e("MainActivity", "onScanResult: " + result.getDevice().getName());
        }

        @Override
        public void onBatchScanResults(final List<ScanResult> results) {
            Log.e("MainActivity", "onBatchScanResults: " + results.size());
        }

        @Override
        public void onScanFailed(final int errorCode) {
            // should never be called
        }

    };

1 个答案:

答案 0 :(得分:0)

如果您使用的是nordic scanning library,请尝试以下操作:

 private void scan(){
    scanner = BluetoothLeScannerCompat.getScanner();
    ScanSettings settings = new ScanSettings.Builder()
            .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).setReportDelay(10)
            .setCallbackType(DEFAULT_KEYS_SEARCH_GLOBAL)
            .setUseHardwareBatchingIfSupported(false).build();
    List<ScanFilter> filters = new ArrayList<>();
    scanner.startScan(filters, settings, mScanCallback);
}