-
Notifications
You must be signed in to change notification settings - Fork 10
Ranging Beacons
Starting ranging is very easy, we need to provide a beacon region that will define which beacons to scan for. Let’s say we’re interested in all beacons. For that, we can define a beacon region—by proximity UUID only. Let’s just use the default Cubeacon UUID: CB10023F-A318-3394-4199-A8730C7C1AEC.
Let’s go to the RangingActivity 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 ranging. This goes inside the RangingActivity 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 ranging beacons
region = new CBRegion("com.eyro.cubeacon.ranging_region",
UUID.fromString("CB10023F-A318-3394-4199-A8730C7C1AEC"));
}Now, the code to start and stop ranging as the activity appears and disappears on screen. You need to implement CBServiceListener before connecting to service. This too goes inside the RangingActivity class:
@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 ranging beacons using region
cubeacon.startRangingBeaconsInRegion(region);
} catch (RemoteException e) {
Log.e(TAG, "Error while start ranging 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 ranging listener turns out to be quite simple:
Cubeacon cubeacon = Cubeacon.getInstance();
cubeacon.addRangingListener(new CBRangingListener() {
@Override
public void didRangeBeaconsInRegion(List<CBBeacon> list, CBRegion region) {
Log.d(TAG, "Found beacon: " + list.size());
}
});IMPORTANT: Because we execute ranging listener from a background serivice. So if you want to update your view from ranging listener, you can wrap your code like below :
runOnUiThread(new Runnable() {
@Override
public void run() {
// run update view here...
}
});