这是我们用来检测 iBeacon 并使用 AltBeacon 库在 Android 服务中获取信标对象的方法。
设置信标管理器
BeaconManager beaconManager = BeaconManager.getInstanceForApplication(this);
beaconManager.setForegroundScanPeriod(5100);
beaconManager.setForegroundBetweenScanPeriod(2000);
beaconManager.setBackgroundScanPeriod(5100);
beaconManager.setBackgroundBetweenScanPeriod(2000);
//Parse IBeacon structure
beaconManager.getBeaconParsers().add(new BeaconParser().
setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"));
beaconManager.bind(this);
开始测距信标
private void startBeaconRangeFinderService() {
beaconManager.setRangeNotifier(new RangeNotifier() {
@Override
public void didRangeBeaconsInRegion(Collection<Beacon> beacons, org.altbeacon.beacon.Region region) {
try {
if (beacons.size() > 0) {
for (Beacon b : beacons) {
processYourBeaconInThisMethod(b);
}
}
} catch (Exception ex) {
Log.e(TAG_BEACON_ACTIVITY, "Error was thrown: " + ex.getMessage());
}
}
});
try {
beaconManager.startRangingBeaconsInRegion(new Region("myRangingUniqueId", null, null, null));
} catch (RemoteException e) {
Log.e(TAG_BEACON_ACTIVITY, "Error was thrown: " + e.getMessage());
}
}