找不到方法android.bluetooth.le.BluetoothLeScanner.startScan

时间:2016-04-21 07:24:05

标签: android android-studio bluetooth-lowenergy

来自acer平板电脑,Acer B1-810 android 4.4.4的错误日志。我正在测试小型BLE应用程序,我得到了这个日志“无法找到方法android.bluetooth.le.BluetoothLeScanner.startScan”,我很困惑,因为BLE在api level 18(4.3)中引入了使用Android 4.4.4,但是“找不到方法android.bluetooth.le.BluetoothLeScanner.startScan”。它显示在日志中。

1 个答案:

答案 0 :(得分:2)

api 21中添加了

BluetoothLeScanner,用于21岁以下的api BluetoothAdapter.startLeScan()

private void startBluetoothLeScan() {
    BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
    if (Build.VERSION.SDK_INT < 21) {
        bluetoothAdapter.startLeScan(new BluetoothAdapter.LeScanCallback() {
            @Override
            public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {

            }
        });
    } else {
        BluetoothLeScanner bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
        ScanSettings scanSettings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                .build();
        List<ScanFilter> scanFilters = new ArrayList<>();
        bluetoothLeScanner.startScan(scanFilters, scanSettings, new ScanCallback() {
            @Override
            public void onScanResult(int callbackType, ScanResult result) {
            }

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

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

请参阅Bluetooth Low Energy文档以获取更多信息