I am using a POJO as a BootStrapNotifier instead of Application class. The POJO has reference to the context. Will background detection start in this way? I am also using this class as MonitorNotifier when the app is in foreground. Is it mandatory to use BootStrapNotifier and RangeNotifier in the same class like shown in the Reference Application? Is this a correct approach? If the app is killed, will the beacon detection start only when power is connected or disconnected or re booted?
Yes, it is possible to use a POJO to receive the callbacks from a RegionBootsrap, but you must still use the onCreate
method of an Android Application
class to construct this POJO and set it up.
The Application
class is needed because its onCreate
method is the first user-executable code that executes when an Android application starts up. The Android Beacon Library’s RegionBootstrap
works because the library sets up a broadcast receiver that looks for BOOT_COMPLETED
, ACTION_POWER_CONNECTED
and ACTION_POWER_DISCONNECTED
events. This broadcast receiver doesn’t do much, but if the app is not running when one of these events happens, it causes the Application
class’ onCreate
method to get executed. It is the creation of a RegionBootstrap
at this time that causes beacon scanning to start in the background and then notify user code when beacons of interest are located.
The code below shows how you set up a POJO called MyPojo
to receive the callbacks from the RegionBootstrap, and register that POJO in the Application
’s onCreate
method. The first parameter of the RegionBootstrap
is the class that will receive the callbacks when beacons are detected.
You can use a POJO like this to set up ranging or do anything else you want -- there is no reason that such code has to reside in an Android Application
class.
public void onCreate() {
super.onCreate();
MyPojo myPojo = new MyPojo(this);
Region region = new Region("backgroundRegion",
null, null, null);
regionBootstrap = new RegionBootstrap(myPojo, region);
}
...
public class MyPojo implements BootstrapNotifier {
private Context mContext;
public MyPojo(Context context) {
mContext = context;
}
public Context getApplicationContext() {
return mContext;
}
public void didEnterRegion(Region region) {
...
}
public void didExitRegion(Region region) {
...
}
public void didDetermineStateForRegion(int state, Region region) {
...
}
}