-
Notifications
You must be signed in to change notification settings - Fork 10
Monitoring Beacon
We need to provide a beacon region that will define which beacons to monitring for. For that, we can define a beacon region—by proximity UUID-major-minor. Let’s just use the default Cubeacon UUID: CB10023F-A318-3394-4199-A8730C7C1AEC
, major: 1
and minor 284
.
Let’s go to the MonitoringActivity
implementation file and set up a second beacon manager. Also, this time, we’ll create a dedicated property to hold the beacon region, since we’ll be using it in two places: to start, and to stop monitoring. This goes inside the MonitoringActivity
class:
private Cubeacon cubeacon;
private CBRegion region;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cubeacon = Cubeacon.getInstance();
// create a new region for monitoring beacon
region = new CBRegion("com.eyro.cubeacon.monitoring_region",
UUID.fromString("CB10023F-A318-3394-4199-A8730C7C1AEC"), 1, 284);
}
Now, the code to start and stop monitoring as the activity appears and disappears on screen. You need to implement CBServiceListener
before connecting to service. This too goes inside the MonitoringActivity
class:
public class MonitoringActivity extends Activity implements CBServiceListener {
@Override
protected void onResume() {
super.onResume();
// check all requirement like is BLE available, is bluetooth on/off,
// location service for Android API 23 or later
if (SystemRequirementManager.checkAllRequirementUsingDefaultDialog(this)) {
// connecting to Cubeacon service when all requirements completed
cubeacon.connect(this);
}
}
@Override
public void onBeaconServiceConnect() {
try {
// start monitoring beacon using region
cubeacon.startMonitoringForRegion(region);
} catch (RemoteException e) {
Log.e(TAG, "Error while start monitoring beacon, " + e);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
// disconnect from Cubeacon service when this activity destroyed
cubeacon.disconnect(this);
}
Having the list pre-sorted by the Cubeacon SDK, and with all the prep work we’ve performed, the monitoring listener turns out to be quite simple:
Cubeacon cubeacon = Cubeacon.getInstance();
cubeacon.addMonitoringListener(new CBMonitoringListener() {
@Override
public void didEnterRegion(CBRegion region) {
Log.d(TAG, "Entering beacon region");
}
@Override
public void didExitRegion(CBRegion region) {
Log.d(TAG, "Exiting beacon region");
}
@Override
public void didDetermineStateForRegion(MonitoringState state, CBRegion region) {
switch (state) {
case INSIDE:
Log.d(TAG, "Change state to entering beacon region");
break;
case OUTSIDE:
Log.d(TAG, "Change state to exiting beacon region");
break;
}
}
});