Detect iBeacon with AltBeacon Library on Android

315 views Asked by At

i'm using the AltBeacon library to detect an iBeacon device. This is the code that i use, based on the AltBeacon's documentation, but the beacon is not detected:

beaconManager = BeaconManager.getInstanceForApplication(this);
beaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"));
beaconManager.bind(this);
beaconManager.addMonitorNotifier(new MonitorNotifier() {
        @Override
        public void didEnterRegion(Region region) {
            Log.i("test", "I just saw an beacon for the first time!");
        }

        @Override
        public void didExitRegion(Region region) {
            Log.i("test", "I no longer see an beacon");
        }

        @Override
        public void didDetermineStateForRegion(int state, Region region) {
            Log.i("test", "I have just switched from seeing/not seeing beacons: "+state);
        }
    });

try {
   beaconManager.startMonitoringBeaconsInRegion(new Region("e2c56db5-dffb-48d2-b060-d0f5a71096e0", null, null, null));
 } catch (RemoteException e) {    }

Is this code wrong?

1

There are 1 answers

3
davidgyoung On

Two issues:

Issue 1:

When you call beaconManager.bind(this); the enclosing class must be an instance of BeaconConsumer (and typically an instance of Application or Activity otherwise you need to chain the BeaconConsumer methods.)

The key point is that you may only call this block:

try { beaconManager.startMonitoringBeaconsInRegion(new Region("e2c56db5-dffb-48d2-b060-d0f5a71096e0", null, null, null)); } catch (RemoteException e) { }

after you have received a callback to onBeaconServicecConnected. This code should usually be in that callback. Because the exception block is empty and logs nothing, I suspect the code is throwing this exception and failing silently. You should always at least log an error in an exception block to help find problems like this.

Issue 2:

The constructor for region should look like this:

new Region("com.mydomain.myapp.region1", Identifier.parse("e2c56db5-dffb-48d2-b060-d0f5a71096e0"), null, null);

Note that the first parameter is a string that serves as a unique identifier for the region so you can later use the same identifier to stop or replace the region being monitored. The second parameter is the ProximityUUID and the third and fourth parameters are the major and minor, respectively.

The way the identifier is constructed in the code shown should work, because it defines a unique id of "e2c56db5-dffb-48d2-b060-d0f5a71096e0" with ProximityUUID/major/minor values that are all null and therefore wildcards. It is, however, misleading, because it suggests it is looking for a specific ProximityUUID when it is not.