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 个打印。