Class BeaconManager


  • public class BeaconManager
    extends Object
    A class used to set up interaction with beacons from an Activity or Service. This class is used in conjunction with BeaconConsumer interface, which provides a callback when the BeaconService is ready to use. Until this callback is made, ranging and monitoring of beacons is not possible. In the example below, an Activity implements the BeaconConsumer interface, binds to the service, then when it gets the callback saying the service is ready, it starts ranging.
    
      public class RangingActivity extends Activity implements BeaconConsumer {
          protected static final String TAG = "RangingActivity";
          private BeaconManager beaconManager = BeaconManager.getInstanceForApplication(this);
          @Override
          protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_ranging);
              beaconManager.bind(this);
          }
          @Override
          protected void onDestroy() {
              super.onDestroy();
              beaconManager.unbind(this);
          }
          @Override
          public void onBeaconServiceConnect() {
              beaconManager.setRangeNotifier(new RangeNotifier() {
                  @Override
                  public void didRangeBeaconsInRegion(Collection beacons, Region region) {
                      if (beacons.size() > 0) {
                          Log.i(TAG, "The first beacon I see is about "+beacons.iterator().next().getDistance()+" meters away.");
                      }
                  }
              });
    
              try {
                  beaconManager.startRangingBeaconsInRegion(new Region("myRangingUniqueId", null, null, null));
              } catch (RemoteException e) {
                  e.printStackTrace();
              }
          }
      }
      
    • Field Detail

      • sInstance

        @Nullable
        protected static volatile BeaconManager sInstance
      • dataRequestNotifier

        @Nullable
        protected RangeNotifier dataRequestNotifier
      • DEFAULT_FOREGROUND_SCAN_PERIOD

        public static final long DEFAULT_FOREGROUND_SCAN_PERIOD
        The default duration in milliseconds of the Bluetooth scan cycle
        See Also:
        Constant Field Values
      • DEFAULT_FOREGROUND_BETWEEN_SCAN_PERIOD

        public static final long DEFAULT_FOREGROUND_BETWEEN_SCAN_PERIOD
        The default duration in milliseconds spent not scanning between each Bluetooth scan cycle
        See Also:
        Constant Field Values
      • DEFAULT_BACKGROUND_SCAN_PERIOD

        public static final long DEFAULT_BACKGROUND_SCAN_PERIOD
        The default duration in milliseconds of the Bluetooth scan cycle when no ranging/monitoring clients are in the foreground
        See Also:
        Constant Field Values
      • DEFAULT_BACKGROUND_BETWEEN_SCAN_PERIOD

        public static final long DEFAULT_BACKGROUND_BETWEEN_SCAN_PERIOD
        The default duration in milliseconds spent not scanning between each Bluetooth scan cycle when no ranging/monitoring clients are in the foreground
        See Also:
        Constant Field Values
      • DEFAULT_EXIT_PERIOD

        public static final long DEFAULT_EXIT_PERIOD
        The default duration in milliseconds of region exit time
        See Also:
        Constant Field Values
      • beaconSimulator

        @Nullable
        protected static BeaconSimulator beaconSimulator
      • distanceModelUpdateUrl

        protected static String distanceModelUpdateUrl
      • rssiFilterImplClass

        protected static Class rssiFilterImplClass
        Default class for rssi filter/calculation implementation
    • Constructor Detail

      • BeaconManager

        protected BeaconManager​(@NonNull
                                Context context)
    • Method Detail

      • setDebug

        public static void setDebug​(boolean debug)
        Set to true if you want to show library debugging.
        Parameters:
        debug - True turn on all logs for this library to be printed out to logcat. False turns off detailed logging.. This is a convenience method that calls setLogger to a verbose logger and enables verbose logging. For more fine grained control, use: LogManager.setLogger(org.altbeacon.beacon.logging.Logger) instead.
      • setForegroundScanPeriod

        public void setForegroundScanPeriod​(long p)
        Sets the duration in milliseconds of each Bluetooth LE scan cycle to look for beacons. This function is used to setup the period before calling bind(org.altbeacon.beacon.BeaconConsumer) or when switching between background/foreground. To have it effect on an already running scan (when the next cycle starts), call updateScanPeriods()
        Parameters:
        p -
      • setForegroundBetweenScanPeriod

        public void setForegroundBetweenScanPeriod​(long p)
        Sets the duration in milliseconds between each Bluetooth LE scan cycle to look for beacons. This function is used to setup the period before calling bind(org.altbeacon.beacon.BeaconConsumer) or when switching between background/foreground. To have it effect on an already running scan (when the next cycle starts), call updateScanPeriods()
        Parameters:
        p -
      • setBackgroundScanPeriod

        public void setBackgroundScanPeriod​(long p)
        Sets the duration in milliseconds of each Bluetooth LE scan cycle to look for beacons. This function is used to setup the period before calling bind(org.altbeacon.beacon.BeaconConsumer) or when switching between background/foreground. To have it effect on an already running scan (when the next cycle starts), call updateScanPeriods()
        Parameters:
        p -
      • setBackgroundBetweenScanPeriod

        public void setBackgroundBetweenScanPeriod​(long p)
        Sets the duration in milliseconds spent not scanning between each Bluetooth LE scan cycle when no ranging/monitoring clients are in the foreground
        Parameters:
        p -
      • setRegionExitPeriod

        public static void setRegionExitPeriod​(long regionExitPeriod)
        Set region exit period in milliseconds
        Parameters:
        regionExitPeriod -
      • getRegionExitPeriod

        public static long getRegionExitPeriod()
        Get region exit milliseconds
        Returns:
        exit region period in milliseconds
      • getInstanceForApplication

        @NonNull
        public static BeaconManager getInstanceForApplication​(@NonNull
                                                              Context context)
        An accessor for the singleton instance of this class. A context must be provided, but if you need to use it from a non-Activity or non-Service class, you can attach it to another singleton or a subclass of the Android Application class.
      • isMainProcess

        public boolean isMainProcess()
        Determines if this BeaconManager instance is associated with the main application process that hosts the user interface. This is normally true unless the scanning service or another servide is running in a separate process.
        Returns:
      • isScannerInDifferentProcess

        public boolean isScannerInDifferentProcess()
        Determines if this BeaconManager instance is not part of the process hosting the beacon scanning service. This is normally false, except when scanning is hosted in a different process. This will always return false until the scanning service starts up, at which time it will be known if it is in a different process.
        Returns:
      • setScannerInSameProcess

        public void setScannerInSameProcess​(boolean isScanner)
        Reserved for internal use by the library.
      • checkIfMainProcess

        protected void checkIfMainProcess()
      • getBeaconParsers

        @NonNull
        public List<BeaconParser> getBeaconParsers()
        Gets a list of the active beaconParsers.
        Returns:
        list of active BeaconParsers
      • checkAvailability

        public boolean checkAvailability()
                                  throws BleNotAvailableException
        Check if Bluetooth LE is supported by this Android device, and if so, make sure it is enabled.
        Returns:
        false if it is supported and not enabled
        Throws:
        BleNotAvailableException - if Bluetooth LE is not supported. (Note: The Android emulator will do this)
      • bind

        public void bind​(@NonNull
                         BeaconConsumer consumer)
        Binds an Android Activity or Service to the BeaconService. The Activity or Service must implement the beaconConsumer interface so that it can get a callback when the service is ready to use.
        Parameters:
        consumer - the Activity or Service that will receive the callback when the service is ready.
      • unbind

        public void unbind​(@NonNull
                           BeaconConsumer consumer)
        Unbinds an Android Activity or Service to the BeaconService. This should typically be called in the onDestroy() method.
        Parameters:
        consumer - the Activity or Service that no longer needs to use the service.
      • isBound

        public boolean isBound​(@NonNull
                               BeaconConsumer consumer)
        Tells you if the passed beacon consumer is bound to the service
        Parameters:
        consumer -
        Returns:
      • isAnyConsumerBound

        public boolean isAnyConsumerBound()
        Tells you if the any beacon consumer is bound to the service
        Returns:
      • setBackgroundMode

        public void setBackgroundMode​(boolean backgroundMode)
        This method notifies the beacon service that the application is either moving to background mode or foreground mode. When in background mode, BluetoothLE scans to look for beacons are executed less frequently in order to save battery life. The specific scan rates for background and foreground operation are set by the defaults below, but may be customized. When ranging in the background, the time between updates will be much less frequent than in the foreground. Updates will come every time interval equal to the sum total of the BackgroundScanPeriod and the BackgroundBetweenScanPeriod.
        Parameters:
        backgroundMode - true indicates the app is in the background
        See Also:
        DEFAULT_FOREGROUND_SCAN_PERIOD, setForegroundScanPeriod(long p), setForegroundBetweenScanPeriod(long p), setBackgroundScanPeriod(long p), setBackgroundBetweenScanPeriod(long p)
      • setEnableScheduledScanJobs

        public void setEnableScheduledScanJobs​(boolean enabled)
        Configures using a `ScanJob` run with the `JobScheduler` to perform scans rather than using a long-running `BeaconService` to do so. Calling with true on devices older than Android L (5.0) will not apply the change as the JobScheduler is not available. This value defaults to true on Android O+ and false on devices with older OS versions. Accepting the default value of false is recommended on Android N and earlier because otherwise beacon scans may be run only once every 15 minutes in the background, and no low power scans may be performed between scanning cycles. Setting this value to false will disable ScanJobs when the app is run on Android 8+, which can prohibit delivery of callbacks when the app is in the background unless the scanning process is running in a foreground service. This method may only be called if bind() has not yet been called, otherwise an `IllegalStateException` is thown.
        Parameters:
        enabled -
      • getScheduledScanJobsEnabled

        public boolean getScheduledScanJobsEnabled()
      • getBackgroundMode

        public boolean getBackgroundMode()
      • getBackgroundScanPeriod

        public long getBackgroundScanPeriod()
      • getBackgroundBetweenScanPeriod

        public long getBackgroundBetweenScanPeriod()
      • getForegroundScanPeriod

        public long getForegroundScanPeriod()
      • getForegroundBetweenScanPeriod

        public long getForegroundBetweenScanPeriod()
      • isBackgroundModeUninitialized

        public boolean isBackgroundModeUninitialized()
        Returns:
        indicator of whether any calls have yet been made to set the background mode
      • setRangeNotifier

        @Deprecated
        public void setRangeNotifier​(@Nullable
                                     RangeNotifier notifier)
        Deprecated.
        replaced by (@link #addRangeNotifier)
        Specifies a class that should be called each time the BeaconService gets ranging data, which is nominally once per second when beacons are detected.

        IMPORTANT: Only one RangeNotifier may be active for a given application. If two different activities or services set different RangeNotifier instances, the last one set will receive all the notifications.

        Parameters:
        notifier - The RangeNotifier to register.
        See Also:
        RangeNotifier
      • addRangeNotifier

        public void addRangeNotifier​(@NonNull
                                     RangeNotifier notifier)
        Specifies a class that should be called each time the BeaconService gets ranging data, which is nominally once per second when beacons are detected.

        Permits to register several RangeNotifier objects.

        The notifier must be unregistered using (@link #removeRangeNotifier)

        Parameters:
        notifier - The RangeNotifier to register.
        See Also:
        RangeNotifier
      • removeRangeNotifier

        public boolean removeRangeNotifier​(@NonNull
                                           RangeNotifier notifier)
        Specifies a class to remove from the array of RangeNotifier
        Parameters:
        notifier - The RangeNotifier to unregister.
        See Also:
        RangeNotifier
      • removeAllRangeNotifiers

        public void removeAllRangeNotifiers()
        Remove all the Range Notifiers.
      • removeAllMonitorNotifiers

        public void removeAllMonitorNotifiers()
        Remove all the Monitor Notifiers.
      • setRegionStatePersistenceEnabled

        public void setRegionStatePersistenceEnabled​(boolean enabled)
        Turns off saving the state of monitored regions to persistent storage so it is retained over app restarts. Defaults to enabled. When enabled, there will not be an "extra" region entry event when the app starts up and a beacon for a monitored region was previously visible within the past 15 minutes. Note that there is a limit to 50 monitored regions that may be persisted. If more than 50 regions are monitored, state is not persisted for any.
        Parameters:
        enabled - true to enable the region state persistence, false to disable it.
      • isRegionStatePersistenceEnabled

        public boolean isRegionStatePersistenceEnabled()
        Indicates whether region state preservation is enabled
        Returns:
      • requestStateForRegion

        public void requestStateForRegion​(@NonNull
                                          Region region)
        Requests the current in/out state on the specified region. If the region is being monitored, this will cause an asynchronous callback on the `MonitorNotifier`'s `didDetermineStateForRegion` method. If it is not a monitored region, it will be ignored.
        Parameters:
        region -
      • applySettings

        public void applySettings()
        Call this method if you are running the scanner service in a different process in order to synchronize any configuration settings, including BeaconParsers to the scanner
        See Also:
        isScannerInDifferentProcess()
      • syncSettingsToService

        protected void syncSettingsToService()
      • updateScanPeriods

        public void updateScanPeriods()
                               throws RemoteException
        Updates an already running scan with scanPeriod/betweenScanPeriod according to Background/Foreground state. Change will take effect on the start of the next scan cycle.
        Throws:
        RemoteException - - If the BeaconManager is not bound to the service.
      • getMonitoringNotifier

        @Deprecated
        @Nullable
        public MonitorNotifier getMonitoringNotifier()
        Deprecated.
        replaced by (@link #getMonitorNotifiers)
        Returns:
        the first registered monitorNotifier
      • getRangingNotifier

        @Deprecated
        @Nullable
        public RangeNotifier getRangingNotifier()
        Deprecated.
        replaced by (@link #getRangeNotifiers)
        Returns:
        the first registered rangeNotifier
      • getMonitoredRegions

        @NonNull
        public Collection<Region> getMonitoredRegions()
        Returns:
        the list of regions currently being monitored
      • getRangedRegions

        @NonNull
        public Collection<Region> getRangedRegions()
        Returns:
        the list of regions currently being ranged
      • getDistanceModelUpdateUrl

        public static String getDistanceModelUpdateUrl()
      • setDistanceModelUpdateUrl

        public static void setDistanceModelUpdateUrl​(@NonNull
                                                     String url)
      • setRssiFilterImplClass

        public static void setRssiFilterImplClass​(@NonNull
                                                  Class c)
      • getRssiFilterImplClass

        public static Class getRssiFilterImplClass()
      • setUseTrackingCache

        public static void setUseTrackingCache​(boolean useTrackingCache)
        Allow the library to use a tracking cache
        Parameters:
        useTrackingCache -
      • setMaxTrackingAge

        public void setMaxTrackingAge​(int maxTrackingAge)
        Set the period of time, in which a beacon did not receive new measurements
        Parameters:
        maxTrackingAge - in milliseconds
      • setBeaconSimulator

        public static void setBeaconSimulator​(BeaconSimulator beaconSimulator)
      • getBeaconSimulator

        @Nullable
        public static BeaconSimulator getBeaconSimulator()
      • setDataRequestNotifier

        protected void setDataRequestNotifier​(@Nullable
                                              RangeNotifier notifier)
      • getDataRequestNotifier

        @Nullable
        protected RangeNotifier getDataRequestNotifier()
      • setNonBeaconLeScanCallback

        public void setNonBeaconLeScanCallback​(@Nullable
                                               NonBeaconLeScanCallback callback)
      • isAndroidLScanningDisabled

        public static boolean isAndroidLScanningDisabled()
        Determines if Android L Scanning is disabled by user selection
        Returns:
      • setAndroidLScanningDisabled

        public static void setAndroidLScanningDisabled​(boolean disabled)
        Allows disabling use of Android L BLE Scanning APIs on devices with API 21+ If set to false (default), devices with API 21+ will use the Android L APIs to scan for beacons
        Parameters:
        disabled -
      • setManifestCheckingDisabled

        public static void setManifestCheckingDisabled​(boolean disabled)
        Allows disabling check of manifest for proper configuration of service. Useful for unit testing
        Parameters:
        disabled -
      • getManifestCheckingDisabled

        public static boolean getManifestCheckingDisabled()
        Returns whether manifest checking is disabled