I’m very new to beacon programming. I’ve created a virtual beacon with Beacon Toy and, using Estimote’s sample code, I’m trying to create an app that plays music when the user enters the beacon’s region, and stops playing when the user exits the region. The “start” part works fine but the “stop” part doesn’t work until about 30 seconds after the start part, even if the user exits the region long before the 30 second interval is finished. Here’s my code:
beaconManager.setMonitoringListener(new BeaconManager.MonitoringListener() {
MediaPlayer mediaPlayer;
@Override
public void onEnteredRegion(Region region, List list) {
showNotification(
"Your gate closes in 47 minutes.",
"Current security wait time is 15 minutes, "
+ "and it's a 5 minute walk from security to the gate. "
+ "Looks like you've got plenty of time!");
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.starsandstripes);
// new MyAsyncTask()
// .execute(mediaPlayer);
mediaPlayer.start();
}
@Override
public void onExitedRegion(Region region) {
Log.i("EXITED", "EXITED"); // Not possible to fire until 30 seconds after onEnteredRegion???
showNotification("Exited", "Exited");
mediaPlayer.stop();
// could add an "exit" notification too if you want (-:
}
});
Some delay in call to the “onExited” is to be expected—to save the phone’s battery, the SDK is not doing Bluetooth scanning all the time, instead, it does the scanning in certain intervals. By default, it’s a 10-second scan every 30 seconds. You can tweak that with the “setBackgroundScanPeriod” method.
Plus, in order to ensure that you really exited the range of the beacon, the SDK requires that the beacon hasn’t been detected for a certain period of time—by default, 10 seconds. This is to make sure that if the beacon temporarily disappears from the phone’s “radar” (e.g., a packet got lost), we don’t trigger a “false” exit. You can tweak that part as well with the “setRegionExitExpiration”.
Add this all together and, with default settings, there might be a delay of up to 40 seconds.
Oh, and before you start tweaking … these values are default for a reason, we’ve done some extensive testing on many Android devices in order to come up with values that provide a good balance between responsiveness, energy drain, and eliminating “false” exits. So when in doubt, it’s better to stick to the defaults (:
Piotr, I see the setRegionExitExpiration method in the Javadocs, but I’m getting a “no such method” message when I use it in my code. Was it introduced in a recent version of the SDK? The dependencies in my Gradle file has the following line: