I have been tasked with fixing some code that uses altbeacon with iBeacons. The detection of beacons works well in foreground but not in background.
In the Activity that scans in foreground mode, on entering background the onStop is used to unbind from the beaconmanager and then call a method in the beaconBkgService like this:
Activity code:
protected void onStop() {
super.onStop();
try {
// Do we need to unbind????
iBeaconManager.unbind(this);
beaconBkgService.startScanning();
} catch (Exception e) {
e.printStackTrace();
}
}
beaconBkgService code:
public class beaconBkgService extends Application implements BootstrapNotifier {
public void startScanning() {
try {
mBeaconManager = BeaconManager.getInstanceForApplication(this);
mBeaconManager.setBackgroundBetweenScanPeriod(3000L);
mBeaconManager.setBackgroundScanPeriod(1000L);
mBeaconManager.setBackgroundMode(true);
if (mRegionBootstrap == null){
mAllBeaconsRegion = new ArrayList<Region>();
for (UserBeacons userBeacon : userBeacons) {
mBeaconsRegion = new Region(userBeacon.identifier, userBeacon.UUID, null, null);
mAllBeaconsRegion.add(mBeaconsRegion);
}
mRegionBootstrap = new RegionBootstrap(this, mAllBeaconsRegion);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Should the Activity onStop call the beacon manager unbind() prior to calling beaconBkgService.startScanning() ? I have tried with and without but cannot anything to work.
The desired outcome is that when the app goes into background, scanning should last for 1 sec every 3 secs but the beaconBkgService didEnterRegion does not fire when a beacon is turned on and the app is in background.
And when I get this to work, how will the ExitRegion be effected if the Activity detects the beacon in foreground, then the user switches to background and exits the beacon area? Will the onExitRegion in the beaconBkgService fire? i.e is the state preserved from foreground to background using RegionBootstrap?