java - 从列表中刷新或删除信标
问题描述
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 个打印。
解决方案
只需摆脱 for 循环。初始化 ArrayList 时,您已经将所有信标添加到列表中。
然后将if
块从 for 循环中取出,并在列表初始化后立即离开。
这样,当信标列表的长度为零时,仍然执行 if 块。
推荐阅读
- php - Running total with group by in MySql
- stored-procedures - Oracle stored procedure combine results
- python - Convert data frame to array with column header
- swift - 在 macOS Mojave 上使侧边栏小部件透明
- fullcalendar - 全日历月视图如何添加自定义列
- ios - iOS 10 上 UIImageView 的 Top Anchor 空间更少
- java - 不同的随机数
- ios - iOS 如何优化数据库查询 Parse swift 4
- html - SVG 之间的图像
- user-interface - 记录 Tcl Tk 测试自动化的用户交互