Yes, you can detect beacons in the background only after the Activity starts, but you still need to create your own Application class that implements BootstrapNotifier .
The reason this is necessary is because of the Android life cycle. Activity can exit it by switching to a new Activity or an operating system terminating in low memory conditions if you take it from the foreground.
In the case of low memory, the entire application, including an instance of the Application class (and the beacon scanning service), terminates with Activity . This case is completely beyond your control, but Android Beacon Library has code for automatically restarting the application and the beacon scanning service a few minutes after that.
The hard part for your purposes is to find out in the onCreate method of the Application class whether it is restarting the application (after shutting down with low memory) or whether the application was first started before Activity .
A good way to do this is to keep the SharedPreferences timestamp for starting the Activity .
So, your Application class may have code like this:
public void onCreate() { ... SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); long lastActivityLaunchTime = prefs.getLong("myapp_activity_launch_time_millis", 0l); if (lastActivityLaunchTime > System.currentTimeMillis()-SystemClock.elapsedRealtime() ) { // If we are in here we have launched the Activity since boot, and this is a restart // after temporary low memory shutdown. Need to start scanning startBeaconScanning(); } } public void startBeaconScanning() { Region region = new Region("backgroundRegion", null, null, null); mRegionBootstrap = new RegionBootstrap(this, region); mBackgroundPowerSaver = new BackgroundPowerSaver(this); }
In your Activity you will also need code to detect its first launch, and if so, start scanning from there.
public void onCreate() { ... SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); long lastActivityLaunchTime = prefs.getLong("myapp_activity_launch_time_millis", 0l); if (lastActivityLaunchTime < System.currentTimeMillis()-SystemClock.elapsedRealtime() ) {
davidgyoung
source share