How can I start / disable background monitoring for beacons at runtime with AltBeacon Library for Android?

大兔子大兔子 提交于 2019-12-11 05:17:46

问题


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.

Specifically at runtime (after a remote http service call) I know:

  • IF beacon tracking should be started at all
  • which regions to monitor

Furthermore I may need to turn it off completely if some condition changes (remotely configured).

What's the correct way with the current version of the library (2.5+) to handle this use case?


回答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 Application onCreate 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".

Region region = new Region("com.example.myapp.boostrapRegion", null, null, null);


来源:https://stackoverflow.com/questions/31588667/how-can-i-start-disable-background-monitoring-for-beacons-at-runtime-with-altb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!