Skip to content Skip to sidebar Skip to footer

How Can I Start / Disable Background Monitoring For Beacons At Runtime With Altbeacon Library For Android?

the AltBeacon documentation say I need to initialize the library in the Application onCreate() for background monitoring. But I have the data needed to initialize it at runtime. Sp

Solution 1:

When using the Android Beacon Library to detect beacons in the background, you construct a RegionBootstrap class in a custom Application class as described in the Starting an App in the Background section of the samples.

This example shows setting up an initial Region in the onCreate method, but there is no reason this needs to be static as in the example. You are welcome to execute code to call a service to get information about whether beacon scanning should be started and what identifiers should be used in the Region definition. If you put this after the response to the web service call, you would simply move this line of code into that callback:

regionBootstrap = new RegionBootstrap(this, region);

For this to work with the custom Application class, the first parameter still needs to be a reference to that class. Note also that there is an alternative constructor for this class that takes a list of Regions in case you want to monitor for more.

If you want to change the regions that are monitored at a later time, then the easiest way to do so is with calls like below:

BeaconManager.getInstanceForApplication(context)
    .stopMonitoringBeaconsInRegion(oldRegion);
BeaconManager.getInstanceForApplication(context)
    .startMonitoringBeaconsInRegion(newRegion);

Note that it is also possible to use the above technique with the initial setup. You could construct a dummy region in the ApplicationonCreate method for instantiating the RegionBootstrap, and then use method calls like above to configure different ones when you get a callback from your web service.

Note that when stopping monitoring of a region, you need a reference to the region. This does not need to be the same object -- the only thing that really matters for stopping monitoring is the Region class' unique identifier. This is a String field used as a key to identify the Region. In the example below, that unique identifier is "com.example.myapp.boostrapRegion".

Regionregion=newRegion("com.example.myapp.boostrapRegion", null, null, null);

Post a Comment for "How Can I Start / Disable Background Monitoring For Beacons At Runtime With Altbeacon Library For Android?"