首页 > 解决方案 > 从列表中刷新或删除信标

问题描述

public void onBeaconServiceConnect() {
    BeaconManager beaconManager = BeaconManager.getInstanceForApplication(this);
    beaconManager.setRangeNotifier(new RangeNotifier() {
        @Override
        public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {

            List<Beacon> beaconList = new ArrayList<Beacon>(beacons);

            for (Beacon beacon : beacons) {


                Beacon.setHardwareEqualityEnforced(true);

                beaconList.add(beacon);

                if (beaconList.size() >= 2) {

                    if (beaconList.get(0).getBluetoothAddress().equals("20:91:48:4C:5A:34") && beaconList.get(1).getBluetoothAddress().equals("20:91:48:4C:5B:AF")) {

                        if (beaconList.get(0).getDistance() < beaconList.get(1).getDistance()) {

                            Log.i("MainActivity", "You're in room 1");

                        }


                    }

                    if (beaconList.get(1).getBluetoothAddress().equals("20:91:48:4C:5A:34") && beaconList.get(0).getBluetoothAddress().equals("20:91:48:4C:5B:AF")) {

                        if (beaconList.get(1).getDistance() < beaconList.get(0).getDistance()) {

                            Log.i("MainActivity", "You're in room 1");

                        }


                    }
                    if (beaconList.get(0).getBluetoothAddress().equals("20:91:48:4C:5B:AF") && beaconList.get(1).getBluetoothAddress().equals("20:91:48:4C:5A:34")) {

                        if (beaconList.get(0).getDistance() < beaconList.get(1).getDistance()) {

                            Log.i("MainActivity", "You're in room 2");

                        }
                    }


                    if (beaconList.get(1).getBluetoothAddress().equals("20:91:48:4C:5B:AF") && beaconList.get(0).getBluetoothAddress().equals("20:91:48:4C:5A:34")) {

                        if (beaconList.get(1).getDistance() < beaconList.get(0).getDistance()) {

                            Log.i("MainActivity", "You're in room 2");

                        }
                    }


                } else {
                    Log.i("MainActivity", "Less than 2 beacons detected");
                }

            }
        }
    });

所以这段代码实际上很好并且可以工作,但是每当我从一个信标离开区域时,列表大小保持为 2 并且else { Log.i("MainActivity", "Less than 2 beacons detected");

部分代码永远不会执行,当信标超出范围时如何删除或刷新信标,因此每当列表中添加了 2 个信标但其中一个信标超出范围时,检测到的信标将少于 2 个打印。

标签: javaandroidbeaconaltbeaconandroid-ibeacon

解决方案


只需摆脱 for 循环。初始化 ArrayList 时,您已经将所有信标添加到列表中。

然后将if块从 for 循环中取出,并在列表初始化后立即离开。

这样,当信标列表的长度为零时,仍然执行 if 块。


推荐阅读