Android BLE 4.0 BluetoothLeScanner ScanCallback onScanResult被多次调用

时间:2016-03-10 09:38:27

标签: android bluetooth-lowenergy android-5.0-lollipop android-bluetooth

我的应用正在通过新的Lollipop API BluetoothLeScanner扫描蓝牙4.0广告设备(TI SensorTag)。

我有一个奇怪的行为:在某些设备(三星Tab4,索尼Xperia M2)上,回拨void onScanResult(int callbackType, ScanResult result)仅在广告阶段被调用一次。在其他设备(三星Galaxy Tab A,Acer Iconia One 10)上,始终会调用回调:每次我收到广告包。

我的直截了当的代码:

public class BluetoothMgr {

    private static BluetoothMgr mBluetoothMgr = null;

    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothLeScanner mBluetoothLeScanner;    

    private BluetoothMgr(){
        BluetoothManager manager = (BluetoothManager) DeviceLiftApplication.getContext().getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = manager.getAdapter();
        mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
    }    

    public static synchronized BluetoothMgr getInstance(){
        if(mBluetoothMgr == null){
            mBluetoothMgr = new BluetoothMgr();
        }

        return mBluetoothMgr;
    }

    public void startScan() {
        ScanFilter filter = new ScanFilter.Builder()
                //.setServiceUuid(Device.THERM_SERVICE)
                .build();
        ArrayList<ScanFilter> filters = new ArrayList<ScanFilter>();
        filters.add(filter);

        ScanSettings settings = new ScanSettings.Builder()
                .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                .build();

        mBluetoothLeScanner.startScan(filters, settings, mScanCallback);
    }

    private ScanCallback mScanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            // This is called 1 or several times depending on devices!!
            processResult(result);
        }

        @Override
        public void onBatchScanResults(List<ScanResult> results) {
            for (ScanResult result : results) {
                processResult(result);
            }
        }

        @Override
        public void onScanFailed(int errorCode) {

        }

        private void processResult(ScanResult result) {

        }
    };

}

0 个答案:

没有答案