I am ranging beacons and my target is to process the beacons collection in didRangeBeaconsInregion so that I get the closest one in the collection and show on screen a string related to the beacon itselt (beacon1=red, beacon2=blue...). My current ibeacons advertising rate is 1Hz (and I can't configure them to increase it yet).
I have tried the following:
public void onBeaconServiceConnect() {
beaconManager.setRangeNotifier(new RangeNotifier() {
@Override
public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
Beacon closest = null;
double distance = 100.0;
logToDisplay(beacons.size() + " beacons in collection");
for (Beacon beacon : beacons) {
if (distance > beacon.getDistance()) {
closest = beacon;
distance = beacon.getDistance();
}
}
if (closest == null) {
logToDisplay(getCurrentTimeStamp() + " | Closest = null");
}
else if (closest.getId3().toInt() == 1) {
logToDisplay(getCurrentTimeStamp() + " | BLUE");
}
else if (closest.getId3().toInt() == 3) {
logToDisplay(getCurrentTimeStamp() + " | RED");
}
else if (closest.getId3().toInt() == 4) {
logToDisplay(getCurrentTimeStamp() + " | GREEN");
} // ... and so on with some more colours
}
});
try {
beaconManager.startRangingBeaconsInRegion(new Region("myRangingUniqueId", null, null, null));
} catch (RemoteException e) { }
}
As far as I know, the didRangeBeaconsinRegion has a beacons collection which is a buffer of the beacons seen in the last second. As a consequence of my beacons having only a 1Hz ad rate, the collection size is very small and I can't get consistent results.
I think that there are two solutions:
Is it possible to do this? How can I do it?
Is this set with something like beaconManager.setForegroundScanPeriod(5000l);
?
Yes, you can do what you say, and it should help make results more consistent.
Add the line you mention right after you first get a beaconManager
instance: beaconManager.setForegroundScanPeriod(5000l);