Java源码示例:org.altbeacon.beacon.BeaconManager
示例1
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "Starting foreground service");
beaconManager = BeaconManager.getInstanceForApplication(getApplicationContext());
Utils.setAltBeaconParsers(beaconManager);
beaconManager.setBackgroundScanPeriod(5000);
Foreground.init(getApplication());
Foreground.get().addListener(listener);
ruuviRangeNotifier = new RuuviRangeNotifier(getApplicationContext(), "AltBeaconFGScannerService");
region = new Region("com.ruuvi.station.leRegion", null, null, null);
startFG();
beaconManager.bind(this);
medic = RuuviScannerApplication.setupMedic(getApplicationContext());
setBackground(); // start in background mode
}
示例2
@Inject
public BleManager(@ForApplication Context context, PreferenceManager prefsManager) {
this.context = context;
// the app manifest requires support for BLE, no need to check explicitly
bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = bluetoothManager.getAdapter();
preferenceManager = prefsManager;
gattManager = new GattManager(prefsManager, this);
// Beaconing
beaconManager = org.altbeacon.beacon.BeaconManager.getInstanceForApplication(context);
beaconManager.getBeaconParsers().clear();
beaconManager.getBeaconParsers().add(new BeaconParser().
setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25"));
Timber.d("setting up background monitoring for beacons and power saving");
Identifier id1 = Identifier.parse(ThunderBoardDevice.THUNDER_BOARD_REACT_UUID_STRING);
Region region = new Region("backgroundRegion", id1, null, null);
regionBootstrap = new ThunderBoardBootstrap(context, this, region);
backgroundPowerSaver = new ThunderBoardPowerSaver(context, preferenceManager);
beaconManager.setBackgroundBetweenScanPeriod(ThunderBoardPowerSaver.DELAY_BETWEEN_SCANS_INACTIVE);
handler = new Handler();
}
示例3
public ThunderBoardPowerSaver(Context context, PreferenceManager preferenceManager) {
if (android.os.Build.VERSION.SDK_INT < 18) {
Timber.d("BackgroundPowerSaver requires API 18 or higher.");
return;
}
if (context instanceof Application) {
((Application) context).registerActivityLifecycleCallbacks(this);
} else {
Timber.e("Context is not an application instance, so we cannot use the BackgroundPowerSaver");
}
this.preferenceManager = preferenceManager;
this.beaconManager = BeaconManager.getInstanceForApplication(context);
}
示例4
/**
* Constructor to bootstrap your Application on an entry/exit from a single region.
*
* @param context
* @param monitorNotifier
* @param region
*/
public RegionBootstrap(final Context context, final MonitorNotifier monitorNotifier, Region region) {
if (context == null) {
throw new NullPointerException("Application Context should not be null");
}
this.context = context.getApplicationContext();
this.monitorNotifier = monitorNotifier;
regions = new ArrayList<Region>();
regions.add(region);
beaconManager = BeaconManager.getInstanceForApplication(context);
beaconConsumer = new InternalBeaconConsumer();
if (beaconManager.isBackgroundModeUninitialized()) {
beaconManager.setBackgroundMode(true);
}
beaconManager.bind(beaconConsumer);
LogManager.d(TAG, "Waiting for BeaconService connection");
}
示例5
/**
* Constructor to bootstrap your Application on an entry/exit from multiple regions
*
* @param context
* @param monitorNotifier
* @param regions
*/
public RegionBootstrap(final Context context, final MonitorNotifier monitorNotifier, List<Region> regions) {
if (context == null) {
throw new NullPointerException("Application Context should not be null");
}
this.context = context.getApplicationContext();
this.monitorNotifier = monitorNotifier;
this.regions = regions;
beaconManager = BeaconManager.getInstanceForApplication(context);
beaconConsumer = new InternalBeaconConsumer();
if (beaconManager.isBackgroundModeUninitialized()) {
beaconManager.setBackgroundMode(true);
}
beaconManager.bind(beaconConsumer);
LogManager.d(TAG, "Waiting for BeaconService connection");
}
示例6
/**
* Constructor to bootstrap your Application on an entry/exit from a single region.
*
* @param application
* @param region
*/
public RegionBootstrap(BootstrapNotifier application, Region region) {
if (application.getApplicationContext() == null) {
throw new NullPointerException("The BootstrapNotifier instance is returning null from its getApplicationContext() method. Have you implemented this method?");
}
this.context = application.getApplicationContext();
regions = new ArrayList<Region>();
regions.add(region);
this.monitorNotifier = application;
beaconManager = BeaconManager.getInstanceForApplication(context);
beaconConsumer = new InternalBeaconConsumer();
if (beaconManager.isBackgroundModeUninitialized()) {
beaconManager.setBackgroundMode(true);
}
beaconManager.bind(beaconConsumer);
LogManager.d(TAG, "Waiting for BeaconService connection");
}
示例7
/**
* Constructor to bootstrap your Application on an entry/exit from multiple regions
*
* @param application
* @param regions
*/
public RegionBootstrap(BootstrapNotifier application, List<Region> regions) {
if (application.getApplicationContext() == null) {
throw new NullPointerException("The BootstrapNotifier instance is returning null from its getApplicationContext() method. Have you implemented this method?");
}
this.context = application.getApplicationContext();
this.regions = regions;
this.monitorNotifier = application;
beaconManager = BeaconManager.getInstanceForApplication(context);
beaconConsumer = new InternalBeaconConsumer();
if (beaconManager.isBackgroundModeUninitialized()) {
beaconManager.setBackgroundMode(true);
}
beaconManager.bind(beaconConsumer);
LogManager.d(TAG, "Waiting for BeaconService connection");
}
示例8
public static BeaconScanDialogFragment getInstance(Context context, DialogCallback dialogCallback, Set<String> knownBeacons) {
BeaconScanDialogFragment fragment = new BeaconScanDialogFragment();
fragment.setLeScanner(CycledLeScanner.createScanner(context, SCAN_TIME_MILLIS, 0L, false,
fragment.new ScanCallback(), null));
fragment.setBeaconParsers(BeaconManager.getInstanceForApplication(context.getApplicationContext()).getBeaconParsers());
fragment.setDialogCallback(dialogCallback);
fragment.setKnownBeacons(knownBeacons);
return fragment;
}
示例9
@Override
public void onCreate() {
super.onCreate();
Foreground.init(getApplication());
Foreground.get().addListener(listener);
Log.d(TAG, "Starting service");
beaconManager = BeaconManager.getInstanceForApplication(this);
Utils.setAltBeaconParsers(beaconManager);
beaconManager.setBackgroundScanPeriod(5000);
region = new Region("com.ruuvi.station.leRegion", null, null, null);
beaconManager.bind(this);
}
示例10
private void bindBeaconManager(BeaconConsumer consumer, Context context) {
if (beaconManager == null) {
beaconManager = BeaconManager.getInstanceForApplication(context.getApplicationContext());
Utils.setAltBeaconParsers(beaconManager);
beaconManager.setBackgroundScanPeriod(5000);
beaconManager.bind(consumer);
} else if (!running) {
running = true;
try {
beaconManager.startRangingBeaconsInRegion(region);
} catch (Exception e) {
Log.d(TAG, "Could not start ranging again");
}
}
}
示例11
public static void setAltBeaconParsers(BeaconManager beaconManager) {
beaconManager.getBeaconParsers().clear();
beaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout(Constants.RuuviV2and4_LAYOUT));
BeaconParser v3Parser = new BeaconParser().setBeaconLayout(Constants.RuuviV3_LAYOUT);
v3Parser.setHardwareAssistManufacturerCodes(new int[]{1177});
beaconManager.getBeaconParsers().add(v3Parser);
BeaconParser v5Parser = new BeaconParser().setBeaconLayout(Constants.RuuviV5_LAYOUT);
v5Parser.setHardwareAssistManufacturerCodes(new int[]{1177});
beaconManager.getBeaconParsers().add(v5Parser);
}
示例12
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
beaconManager = BeaconManager.getInstanceForApplication(getActivity());
beaconManager.getBeaconParsers().add(new BeaconParser()
.setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"));
RxPermissions.getInstance(getContext())
.request(Manifest.permission.ACCESS_COARSE_LOCATION)
.subscribe(new Observer<Boolean>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(Boolean granted) {
checkinBtn.setEnabled(true);
}
});
}
示例13
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMainTv = (TextView) findViewById(R.id.main_tv);
beaconManager = BeaconManager.getInstanceForApplication(this);
// To detect proprietary beacons, you must add a line like below corresponding to your beacon
// type. Do a web search for "setBeaconLayout" to get the proper expression.
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);
}
示例14
public BeaconsAndroidModule(ReactApplicationContext reactContext) {
super(reactContext);
Log.d(LOG_TAG, "BeaconsAndroidModule - started");
this.mReactContext = reactContext;
this.mApplicationContext = reactContext.getApplicationContext();
this.mBeaconManager = BeaconManager.getInstanceForApplication(mApplicationContext);
// Detect iBeacons ( http://stackoverflow.com/questions/25027983/is-this-the-correct-layout-to-detect-ibeacons-with-altbeacons-android-beacon-li )
addParser("m:0-3=4c000215,i:4-19,i:20-21,i:22-23,p:24-24");
mBeaconManager.bind(this);
}
示例15
public ThunderBoardBootstrap(Context context, RangeNotifier rangeNotifier, Region region) {
this.context = context;
this.rangeNotifier = rangeNotifier;
beaconManager = BeaconManager.getInstanceForApplication(context);
regions = new ArrayList<>();
regions.add(region);
beaconConsumer = new InternalBeaconConsumer();
beaconManager.bind(beaconConsumer);
Timber.d("Waiting for BeaconService connection");
}
示例16
public ThunderBoardBootstrap(Context context, RangeNotifier rangeNotifier, List<Region> regions) {
this.context = context;
beaconManager = BeaconManager.getInstanceForApplication(context);
this.regions = regions;
beaconConsumer = new InternalBeaconConsumer();
beaconManager.bind(beaconConsumer);
Timber.d("Waiting for BeaconService connection");
}
示例17
@Override
public void onCreate() {
super.onCreate();
config = ConfigImpl.getInstance(getApplicationContext());
beaconManager = BeaconManager.getInstanceForApplication(this);
beaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout(config.getBeaconParserLayout()));
beaconManager.bind(this);
clientsManager = new ClientsManager(this, beaconManager);
}
示例18
@Provides
@Singleton
public BeaconManager provideBeaconManager() {
BeaconManager manager = BeaconManager.getInstanceForApplication(application);
//manager.setDebug(true);
return manager;
}
示例19
@Override
public void onReceive(Context context, Intent intent) {
LogManager.d(TAG, "onReceive called in startup broadcast receiver");
if (android.os.Build.VERSION.SDK_INT < 18) {
LogManager.w(TAG, "Not starting up beacon service because we do not have API version 18 (Android 4.3). We have: %s", android.os.Build.VERSION.SDK_INT);
return;
}
BeaconManager beaconManager = BeaconManager.getInstanceForApplication(context.getApplicationContext());
if (beaconManager.isAnyConsumerBound() || beaconManager.getScheduledScanJobsEnabled()) {
int bleCallbackType = intent.getIntExtra(BluetoothLeScanner.EXTRA_CALLBACK_TYPE, -1); // e.g. ScanSettings.CALLBACK_TYPE_FIRST_MATCH
if (bleCallbackType != -1) {
LogManager.d(TAG, "Passive background scan callback type: "+bleCallbackType);
LogManager.d(TAG, "got Android O background scan via intent");
int errorCode = intent.getIntExtra(BluetoothLeScanner.EXTRA_ERROR_CODE, -1); // e.g. ScanCallback.SCAN_FAILED_INTERNAL_ERROR
if (errorCode != -1) {
LogManager.w(TAG, "Passive background scan failed. Code; "+errorCode);
}
ArrayList<ScanResult> scanResults = intent.getParcelableArrayListExtra(BluetoothLeScanner.EXTRA_LIST_SCAN_RESULT);
ScanJobScheduler.getInstance().scheduleAfterBackgroundWakeup(context, scanResults);
}
else if (intent.getBooleanExtra("wakeup", false)) {
LogManager.d(TAG, "got wake up intent");
}
else {
LogManager.d(TAG, "Already started. Ignoring intent: %s of type: %s", intent,
intent.getStringExtra("wakeup"));
}
}
else {
LogManager.d(TAG, "No consumers are bound. Ignoring broadcast receiver.");
}
}
示例20
/**
* Constructs a new BackgroundPowerSaver using the default background determination strategy
*
* @param context
*/
public BackgroundPowerSaver(Context context) {
if (android.os.Build.VERSION.SDK_INT < 18) {
LogManager.w(TAG, "BackgroundPowerSaver requires API 18 or higher.");
}
beaconManager = BeaconManager.getInstanceForApplication(context);
((Application)context.getApplicationContext()).registerActivityLifecycleCallbacks(this);
}
示例21
@Override
@MainThread
@SuppressLint("WrongThread")
public void onCycleEnd() {
if (BeaconManager.getBeaconSimulator() != null) {
LogManager.d(TAG, "Beacon simulator enabled");
// if simulatedScanData is provided, it will be seen every scan cycle. *in addition* to anything actually seen in the air
// it will not be used if we are not in debug mode
if (BeaconManager.getBeaconSimulator().getBeacons() != null) {
if (0 != (mContext.getApplicationInfo().flags &= ApplicationInfo.FLAG_DEBUGGABLE)) {
LogManager.d(TAG, "Beacon simulator returns "+BeaconManager.getBeaconSimulator().getBeacons().size()+" beacons.");
for (Beacon beacon : BeaconManager.getBeaconSimulator().getBeacons()) {
// This is an expensive call and we do not want to block the main thread.
// But here we are in debug/test mode so we allow it on the main thread.
//noinspection WrongThread
processBeaconFromScan(beacon);
}
} else {
LogManager.w(TAG, "Beacon simulations provided, but ignored because we are not running in debug mode. Please remove beacon simulations for production.");
}
} else {
LogManager.w(TAG, "getBeacons is returning null. No simulated beacons to report.");
}
}
else {
if (LogManager.isVerboseLoggingEnabled()) {
LogManager.d(TAG, "Beacon simulator not enabled");
}
}
mDistinctPacketDetector.clearDetections();
mMonitoringStatus.updateNewlyOutside();
processRangeData();
}
示例22
private void applySettingsToScheduledJob(Context context, BeaconManager beaconManager, ScanState scanState) {
scanState.applyChanges(beaconManager);
LogManager.d(TAG, "Applying scan job settings with background mode "+scanState.getBackgroundMode());
// if this is the first time we want to schedule a job and we are in background mode
// trigger an immediate scan job in order to install the hw filter
boolean startBackgroundImmediateScan = false;
if (this.mBackgroundScanJobFirstRun && scanState.getBackgroundMode()) {
LogManager.d(TAG, "This is the first time we schedule a job and we are in background, set immediate scan flag to true in order to trigger the HW filter install.");
startBackgroundImmediateScan = true;
}
schedule(context, scanState, startBackgroundImmediateScan);
}
示例23
private boolean startScanning() {
BeaconManager beaconManager = BeaconManager.getInstanceForApplication(getApplicationContext());
beaconManager.setScannerInSameProcess(true);
if (beaconManager.isMainProcess()) {
LogManager.i(TAG, "scanJob version %s is starting up on the main process", BuildConfig.VERSION_NAME);
}
else {
LogManager.i(TAG, "beaconScanJob library version %s is starting up on a separate process", BuildConfig.VERSION_NAME);
ProcessUtils processUtils = new ProcessUtils(ScanJob.this);
LogManager.i(TAG, "beaconScanJob PID is "+processUtils.getPid()+" with process name "+processUtils.getProcessName());
}
ModelSpecificDistanceCalculator defaultDistanceCalculator = new ModelSpecificDistanceCalculator(ScanJob.this, BeaconManager.getDistanceModelUpdateUrl());
Beacon.setDistanceCalculator(defaultDistanceCalculator);
return restartScanning();
}
示例24
public boolean markOutsideIfExpired() {
if (inside) {
if (lastSeenTime > 0 && SystemClock.elapsedRealtime() - lastSeenTime > BeaconManager.getRegionExitPeriod()) {
LogManager.d(TAG, "We are newly outside the region because the lastSeenTime of %s "
+ "was %s seconds ago, and that is over the expiration duration "
+ "of %s", lastSeenTime, SystemClock.elapsedRealtime() - lastSeenTime,
BeaconManager.getRegionExitPeriod());
markOutside();
return true;
}
}
return false;
}
示例25
private void startForegroundIfConfigured() {
BeaconManager beaconManager = BeaconManager.getInstanceForApplication(
this.getApplicationContext());
Notification notification = beaconManager
.getForegroundServiceNotification();
int notificationId = beaconManager
.getForegroundServiceNotificationId();
if (notification != null &&
Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
this.startForeground(notificationId, notification);
}
}
示例26
public void applyChanges(BeaconManager beaconManager) {
mBeaconParsers = new HashSet<>(beaconManager.getBeaconParsers());
mForegroundScanPeriod = beaconManager.getForegroundScanPeriod();
mForegroundBetweenScanPeriod = beaconManager.getForegroundBetweenScanPeriod();
mBackgroundScanPeriod = beaconManager.getBackgroundScanPeriod();
mBackgroundBetweenScanPeriod = beaconManager.getBackgroundBetweenScanPeriod();
mBackgroundMode = beaconManager.getBackgroundMode();
ArrayList<Region> existingMonitoredRegions = new ArrayList<>(mMonitoringStatus.regions());
ArrayList<Region> existingRangedRegions = new ArrayList<>(mRangedRegionState.keySet());
ArrayList<Region> newMonitoredRegions = new ArrayList<>(beaconManager.getMonitoredRegions());
ArrayList<Region> newRangedRegions = new ArrayList<>(beaconManager.getRangedRegions());
LogManager.d(TAG, "ranged regions: old="+existingRangedRegions.size()+" new="+newRangedRegions.size());
LogManager.d(TAG, "monitored regions: old="+existingMonitoredRegions.size()+" new="+newMonitoredRegions.size());
for (Region newRangedRegion: newRangedRegions) {
if (!existingRangedRegions.contains(newRangedRegion)) {
LogManager.d(TAG, "Starting ranging region: "+newRangedRegion);
mRangedRegionState.put(newRangedRegion, new RangeState(new Callback(mContext.getPackageName())));
}
}
for (Region existingRangedRegion: existingRangedRegions) {
if (!newRangedRegions.contains(existingRangedRegion)) {
LogManager.d(TAG, "Stopping ranging region: "+existingRangedRegion);
mRangedRegionState.remove(existingRangedRegion);
}
}
LogManager.d(TAG, "Updated state with "+newRangedRegions.size()+" ranging regions and "+newMonitoredRegions.size()+" monitoring regions.");
this.save();
}
示例27
private RssiFilter getFilter() {
if (mFilter == null) {
//set RSSI filter
try {
Constructor cons = BeaconManager.getRssiFilterImplClass().getConstructors()[0];
mFilter = (RssiFilter)cons.newInstance();
} catch (Exception e) {
LogManager.e(TAG, "Could not construct RssiFilterImplClass %s", BeaconManager.getRssiFilterImplClass().getName());
}
}
return mFilter;
}
示例28
public SettingsData collect(@NonNull Context context) {
BeaconManager beaconManager = BeaconManager.getInstanceForApplication(context);
mBeaconParsers = new ArrayList<>(beaconManager.getBeaconParsers());
mRegionStatePersistenceEnabled = beaconManager.isRegionStatePersistenceEnabled();
mAndroidLScanningDisabled = beaconManager.isAndroidLScanningDisabled();
mRegionExitPeriod = BeaconManager.getRegionExitPeriod();
mUseTrackingCache = RangeState.getUseTrackingCache();
mHardwareEqualityEnforced = Beacon.getHardwareEqualityEnforced();
return this;
}
示例29
public static CycledLeScanner createScanner(Context context, long scanPeriod, long betweenScanPeriod, boolean backgroundFlag, CycledLeScanCallback cycledLeScanCallback, BluetoothCrashResolver crashResolver) {
boolean useAndroidLScanner = false;
boolean useAndroidOScanner = false;
if (android.os.Build.VERSION.SDK_INT < 18) {
LogManager.w(TAG, "Not supported prior to API 18.");
return null;
}
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
LogManager.i(TAG, "This is pre Android 5.0. We are using old scanning APIs");
useAndroidLScanner = false;
}
else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
if (BeaconManager.isAndroidLScanningDisabled()) {
LogManager.i(TAG, "This is Android 5.0, but L scanning is disabled. We are using old scanning APIs");
useAndroidLScanner = false;
} else {
LogManager.i(TAG, "This is Android 5.0. We are using new scanning APIs");
useAndroidLScanner = true;
}
}
else {
LogManager.i(TAG, "Using Android O scanner");
useAndroidOScanner = true;
}
if (useAndroidOScanner) {
return new CycledLeScannerForAndroidO(context, scanPeriod, betweenScanPeriod, backgroundFlag, cycledLeScanCallback, crashResolver);
}
else if (useAndroidLScanner) {
return new CycledLeScannerForLollipop(context, scanPeriod, betweenScanPeriod, backgroundFlag, cycledLeScanCallback, crashResolver);
} else {
return new CycledLeScannerForJellyBeanMr2(context, scanPeriod, betweenScanPeriod, backgroundFlag, cycledLeScanCallback, crashResolver);
}
}
示例30
@Before
public void before() {
org.robolectric.shadows.ShadowLog.stream = System.err;
LogManager.setLogger(Loggers.verboseLogger());
LogManager.setVerboseLoggingEnabled(true);
BeaconManager.setManifestCheckingDisabled(true);
Context context = RuntimeEnvironment.application;
new MonitoringStatus(context).clear();
}