Over a million developers have joined DZone.

Getting Started With Beacons and Couchbase Lite Android

Ever wanted to get started with beacons? Here is your chance!

· IoT Zone

Access the survey results 'State of Industrial Internet Application Development' to learn about latest challenges, trends and opportunities with Industrial IoT, brought to you in partnership with GE Digital.

Beacons. These small devices might become ubiquitous in the future. It started with iBeacons from Apple, AltBeacon, and Google is now getting it's own platform called Eddystone. This is going to be interesting.

If you don't know what a beacon is, it's a dumb thing that only knows how to emit its presence to the world. That is the sole purpose of a beacon. Telling to whoever is listening in range that it's here and it's name is e9ae6b9f-7238-4df6-8497-dec29ebf4184 (or something like that). It does that using Bluetooth LE (Or Bluetooth Low Energy, BLE, Bluetooth Smart).

This means that a beacon is useful when you have an application that know how to react to the beacon's presence. The app needs to know what to do when the user encounters the beacon. And maybe the thing to do will change in time. If you walk across a beacon in a supermarket, the app might show you what is currently on sales. And obviously this will change in time. So a good thing when working with beacons is to be able to repurpose them. This is something that Couchbase Mobile can offer you. Easily sync back a new behavior for a particular beacon.

And of course since it works offline, it can always do the intended thing even if the user has no network connection. You can also save a document locally with information about the user being in range of the beacon and sync it back later to the server. It can give you some interesting data about your users behavior in a place without or with poor network connectivity. Think about any big outdoor event for instance.

I started toying around with these ideas for various conferences and meetups, here's how to get started with Beacons and Android.

Testing Beacons

Being able to test beacons is the first thing I wanted to do. And the reason to that was, I have no beacons :). Which my sound weird I know. But a beacon is just a low energy bluetooth device. I have bluetooth on my mac, I also have some BLE dongles and a RaspberryPi, everything should be fine.

The wonderful people at Radius Networks built a VM image that can very simply act as a beacon. Everything is explained on their website. If you have a Mac and want to use its Bluetooth hardware in VirtualBox, know that you have to disable it first for the VM host. If you have bluetooth dongle than it's really quick, just make sure VirtualBox is configured to use it.

They also built PiBeacon. It's pretty much a Beacon development kit based on the RaspberryPI. And you can download the image for the Raspberry here. Complete instructions can also be found on their website.

Once you have the Raspberry running with their image, you can SSH into it and run something like

 sudo beacon transmit -A -f 5 -1 00000000-0000-0000-0000-000000000000 -2 0 -3 0 -r 0

This will simulate a beacon transmitter. They have three identifiers. A UUID, a major version and a minor version. This is part of the common layer between every Beacons format like AltBeacon(Open format), iBeacon(Apple) and EddyStone(Google). And this is what apps use to identify beacons.

I wanted to make sure everything was working correctly so I installed BeaconScanner on my Mac and another Beacon scanning app on my phone. They both picked up the signal so I was ready to work on my app.

 Android and Beacons

I wanted to keep everything as simple as possible so I went for the AltBeacon stack. Everything is open source and they have a nice Android library. They also have nice, easy to undertand code samples that made it easy to start. So first things first, include the right dependency to your app. Start by adding the JCenter maven repository:

repositories {

Then add the actual library:

dependencies {
    compile 'org.altbeacon:android-beacon-library:${altbeacon.version}'

Something else you can modify right of is adding the right permission to your application AndroidManifest.xml:

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

There are basically two things you can do with Couchbase Mobile. You can act as a client and react to a beacon presence, or you can act as a backend and configure the beacons.

Let's start by the code that initialize the beacon background service. In your Application, upon create, you can execute the following code:

    BeaconManager beaconManager = org.altbeacon.beacon.BeaconManager.getInstanceForApplication(this);
    Log.d(TAG, "setting up background monitoring for beacons and power saving");
    // wake up the app when a beacon is seen
    Region region = new Region("backgroundRegion",
            null, null, null);
    regionBootstrap = new RegionBootstrap(this, region);
    backgroundPowerSaver = new BackgroundPowerSaver(this);

I have setup some aggressive timing for testing purposing. You would use longer duration in production. My Application class also implements the BootstrapNotifier interface. The didEnterRegion method allows a specific activity to be launched when coming in range of a beacon.

    public void didEnterRegion(Region region) {
        // In this example, this class sends a notification to the user whenever a Beacon
        // matching a Region (defined above) are first seen.
        Log.d(TAG, "did enter region.");
        if (!haveDetectedBeaconsSinceBoot) {
            Log.d(TAG, "auto launching MainActivity");

            // The very first time since boot that we detect an beacon, we launch the
            // MainActivity
            Intent intent = new Intent(this, BeaconListActivity.class);
            // Important:  make sure to add android:launchMode="singleInstance" in the manifest
            // to keep multiple copies of this activity from getting created if the user has
            // already manually launched the app.
            haveDetectedBeaconsSinceBoot = true;
        } else {
            if (beaconListActivity != null) {
                // If the Monitoring Activity is visible, we log info about the beacons we have
                // seen on its display
                Log.i(TAG, "I see a beacon again");
            } else {
                // If we have already seen beacons before, but the monitoring activity is not in
                // the foreground, we send a notification to the user on subsequent detections.
                Log.d(TAG, "Sending notification.");

This activity will contain the code you want to show depending on the beacon ID for instance. Or maybe you just want to save a document to log that the current user has been in range of a particular beacon. Which is the first thing I want to do. So I need an activity implementing the BeaconConsumer interface.

    public void onBeaconServiceConnect() {

        beaconManager.setRangeNotifier(new RangeNotifier() {
            public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
                if (beacons.size() > 0) {
                    Beacon firstBeacon = beacons.iterator().next();
                    Document beaconVisit = database.createDocument();
                    Map<String, Object> properties = new HashMap<String, Object>();
                    properties.put("type", "beacon-visit");
                    properties.put("channel", firstBeacon.getId1().toString() + firstBeacon.getId2().toString() + firstBeacon.getId3().toString());
                    properties.put("visitDate", System.currentTimeMillis());
                    try {
                    } catch (CouchbaseLiteException e) {
                        throw new RuntimeException(e);
        try {
            beaconManager.startRangingBeaconsInRegion(new Region("myRangingUniqueId", null, null, null));
        } catch (RemoteException e) {
            throw new RuntimeException(e);

This is some very basic code but you get the idea. At this time you could also sync a channel named after the identifier of the Beacon. This way you get all the information you need to display meaningful information to the user. And if this information change over time, all you have to do is modify the document containing the beacon behavior and sync it back to all users. It's really easy to build a beacon backend with the Sync Gateway REST API :)

So what do you think about Beacons? Are you a user already? Would you like us to talk more about it? Please let us know what you think!

The IoT Zone is brought to you in partnership with GE Digital.  Discover how IoT developers are using Predix to disrupt traditional industrial development models.


Published at DZone with permission of Laurent Doguin, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}