onLeScan在发现蓝牙设备时调用了两次

时间:2016-12-02 08:52:03

标签: android bluetooth bluetooth-lowenergy

我试图发现蓝牙低能耗设备,但我对onLeScan方法有疑问。它被调用两次,因此所有设备都加倍了。

我用来启动扫描的方法:

private void scanLeDevice(final boolean enable) {
        if (enable) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    bluetoothAdapter.stopLeScan(getLeScanCallback());
                    scanning = false;
                }
            }, SCAN_PERIOD);

            scanning = true;
            bluetoothAdapter.startLeScan(getLeScanCallback());
        } else {
            bluetoothAdapter.stopLeScan(getLeScanCallback());
            scanning = false;
        }
    }

返回LeScanCallback的方法:

private BluetoothAdapter.LeScanCallback getLeScanCallback(){
        BluetoothAdapter.LeScanCallback leScanCallback =
                new BluetoothAdapter.LeScanCallback() {
                    @Override
                    public void onLeScan(final BluetoothDevice bluetoothDevice, int rssi
                            , byte[] scanRecord) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Log.d(TAG, "device found");
                                Device device = new Device();
                                device.setName(bluetoothDevice.getName());
                                device.setAddress(bluetoothDevice.getAddress());
                                devices.add(device);
                                deviceListAdapter.notifyDataSetChanged();
                            }
                        });
                    }
                };

        return leScanCallback;
    }

2 个答案:

答案 0 :(得分:8)

是的,如果BLE设备的广告周期与扫描周期相比足够频繁,则在扫描周期内可能会多次出现。因此,您应该识别每个BLE设备(可能带有名称或地址),并将它们仅添加到列表中一次。您可以保留最近看到的信标的单独列表,或者只检查devices是否已包含找到的设备,并避免添加重复项。 (或者使用Set代替List。如果列表中已存在BLE设备,则只需更新任何数据(如果显示RSSI)。您可能需要覆盖equals()中的hashCode()Device,以使List.contains()Set正常工作

答案 1 :(得分:0)

我知道这是很久以前问过的,我正在这里发布我的解决方案。该代码的问题是在scanLeDevice(true)中调用了protected void onResume()。为什么这样叫两次?在这里Why is my onResume being called twice?

您只需要在此处更新逻辑即可。

if (!scanning ) {
//If not scanning start scanning
 mLeDeviceListAdapter = new LeDeviceListAdapter();
            // setListAdapter(mLeDeviceListAdapter);
            dialog = ProgressDialog.show(AdjActivity.this, "Searching for the Ring",
                    "Scanning for Ring. Please wait...", true);
            scanLeDevice(true);
}