BluetoothLeScanner不返回任何蓝牙设备

时间:2020-11-02 22:17:47

标签: android android-studio bluetooth bluetooth-lowenergy

我有一种扫描蓝牙设备的方法,经过一定时间后会停止,但是当我到达此方法时,它会到达mBluetoothLeScanner拥有的.startScan方法,并且只会停止。扫描完成后,我最终在哈希图中找不到设备。

public Scanner_BTLE(MainActivity mainActivity, long scanPeriod, int signalStrength){
    ma = mainActivity;

    mHandler = new Handler();

    this.scanPeriod = 5000;
    this.signalStrength = signalStrength;

    final BluetoothManager bluetoothManager = (BluetoothManager) ma.getSystemService(Context.BLUETOOTH_SERVICE);

    mBluetoothAdapter = bluetoothManager.getAdapter();
    mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
}

这是开始扫描的方法,它将在下面实例化带有mScanCallback的mBluetoothScanner的startScan方法。

private void scanLeDevice(final boolean enable){
    //Start Scanning
    if(enable && !mScanning){
        Utils.toast(ma.getApplication(), "Starting scan...");
        //Stop scanning after 5 seconds
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Utils.toast(ma.getApplicationContext(), "Stopping scan...");
                mScanning = false;
                mBluetoothLeScanner.stopScan(mScanCallBack);
                ma.stopScan();
            }
        }, scanPeriod);
        mScanning = true;
        mBluetoothLeScanner.startScan(mScanCallBack);
    }
    else{
        mScanning = false;
        mBluetoothLeScanner.stopScan(mScanCallBack);
    }
}

private final ScanCallback mScanCallBack =
    new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);
            if(result.getRssi() > signalStrength){
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        Utils.toast(ma.getApplicationContext(), result.getDevice().getName());
                        //Add found bluetooth device to a hash map
                        ma.addDevice(result.getDevice(), result.getRssi());
                    }
                });
            }
        }
    };

这是我清单中包含的内容

<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COURSE_LOCATION" />

0 个答案:

没有答案