Search code examples
ibeaconibeacon-androidandroid-ibeacon

Error when updating the scan period with Android beacon Library


I am trying to change the scan period with android beacon library. This is my code

 BeaconManager beaconManager = BeaconManager.getInstanceForApplication(this);
        beaconManager = BeaconManager.getInstanceForApplication(this);

        beaconManager.getBeaconParsers().add(new BeaconParser().
                setBeaconLayout("m:0-3=4c000215,i:4-19,i:20-21,i:22-23,p:24-24"));
        beaconManager.bind(this);

        try {
            beaconManager.setForegroundScanPeriod(50l); // 1100 mS
            beaconManager.setForegroundBetweenScanPeriod(0l); // 0ms
            beaconManager.updateScanPeriods();
        }
        catch (RemoteException e) {
            Log.e("error", e.getMessage());
        }

I tried different devices but I always get this error The BeaconManager is not bound to the service. Call beaconManager.bind(BeaconConsumer consumer) and wait for a callback to onBeaconServiceConnect()

I think the value of the scan period changes even if I get this error but I am not sure


Solution

  • You cannot call beaconManager.updateScanPeriods(); until after you get the callback to onBeaconServiceConnect() otherwise you get the error mentioned in the question. Understand that the call to bind() stats up the beacon scanning service, which is not instantaneous. When you make the call to update the scan periods, it will fail if the service is not started up yet -- it takes a second or two.

    Two options:

    • Move the code to set the scan periods inside onBeaconServiceConnect().
    • Move the code that sets the foreground and background scan periods before the call to bind() and then remove the beaconManager.updateScanPeriods(); line. If you set the scan periods before calling bind, they will automatically be applied when the service starts up.