startLeScan replacement to current api

前端 未结 5 565
北海茫月
北海茫月 2020-12-14 01:18

Goal is to read the values of a bluetooth LE heart rate monitor.

Using google\'s sample, I get

private void scanLeDevice(final boolean enable) {
             


        
5条回答
  •  庸人自扰
    2020-12-14 01:59

    Thank you all for your responses. To Summarize the answer to this question I'll add my final code snippet.

    private BluetoothAdapter mBluetoothAdapter;
    
    
    private ScanCallback mLeScanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);
        }
    
        @Override
        public void onBatchScanResults(List results) {
            super.onBatchScanResults(results);
        }
    
        @Override
        public void onScanFailed(int errorCode) {
            super.onScanFailed(errorCode);
        }
    };
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BluetoothManager bluetoothManager = (BluetoothManager) getActivity().getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();
    }
    
    
    private void scanLeDevice(final boolean enable) {
    
        final BluetoothLeScanner bluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
    
        if (enable) {
            // Stops scanning after a pre-defined scan period.
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mScanning = false;
    
                    bluetoothLeScanner.stopScan(mLeScanCallback);
                }
            }, SCAN_PERIOD);
    
            mScanning = true;
            bluetoothLeScanner.startScan(mLeScanCallback);
        } else {
            mScanning = false;
            bluetoothLeScanner.stopScan(mLeScanCallback);
        }
    }
    

提交回复
热议问题