Java Code Examples for org.altbeacon.beacon.logging.LogManager#w()

The following examples show how to use org.altbeacon.beacon.logging.LogManager#w() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * Tells the <code>BeaconService</code> to stop looking for beacons that match the passed
 * <code>Region</code> object.  Note that the Region's unique identifier is used to match it to
 * an existing monitored Region.
 *
 * @param region
 * @see BeaconManager#setMonitorNotifier(MonitorNotifier)
 * @see BeaconManager#startMonitoringBeaconsInRegion(Region region)
 * @see MonitorNotifier
 * @see Region
 */
@TargetApi(18)
public void stopMonitoringBeaconsInRegion(@NonNull Region region) throws RemoteException {
    if (!isBleAvailableOrSimulated()) {
        LogManager.w(TAG, "Method invocation will be ignored.");
        return;
    }
    if (determineIfCalledFromSeparateScannerProcess()) {
        return;
    }
    if (mScheduledScanJobsEnabled) {
        MonitoringStatus.getInstanceForApplication(mContext).removeRegion(region);
    }
    applyChangesToServices(BeaconService.MSG_STOP_MONITORING, region);
    if (isScannerInDifferentProcess()) {
        MonitoringStatus.getInstanceForApplication(mContext).removeLocalRegion(region);
    }
}
 
Example 2
@RequiresApi(21)
private void cycleBluetooth() {
    LogManager.d(TAG, "Power cycling bluetooth");
    LogManager.d(TAG, "Turning Bluetooth off.");
    if (mAdapter != null) {
        this.mAdapter.disable();
        this.mHandler.postDelayed(new Runnable() {
            public void run() {
                LogManager.d(BluetoothMedic.TAG, "Turning Bluetooth back on.");
                if (BluetoothMedic.this.mAdapter != null) {
                    BluetoothMedic.this.mAdapter.enable();
                }
            }
        }, 1000L);
    }
    else {
        LogManager.w(TAG, "Cannot cycle bluetooth.  Manager is null.");
    }
}
 
Example 3
private void cancelDiscovery() {
    try {
        Thread.sleep(TIME_TO_LET_DISCOVERY_RUN_MILLIS);
        if (!discoveryStartConfirmed) {
            LogManager.w(TAG, "BluetoothAdapter.ACTION_DISCOVERY_STARTED never received.  Recovery may fail.");
        }

        final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        if (adapter.isDiscovering()) {
            LogManager.d(TAG, "Cancelling discovery");
            adapter.cancelDiscovery();
        }
        else {
            LogManager.d(TAG, "Discovery not running.  Won't cancel it");
        }
    } catch (InterruptedException e) {
        LogManager.d(TAG, "DiscoveryCanceller sleep interrupted.");
    }
}
 
Example 4
/**
 * Stops this beacon from advertising
 */
public void stopAdvertising() {
    if (!mStarted) {
        LogManager.d(TAG, "Skipping stop advertising -- not started");
        return;
    }
    LogManager.d(TAG, "Stopping advertising with object %s", mBluetoothLeAdvertiser);
    mAdvertisingClientCallback = null;
    try {
        mBluetoothLeAdvertiser.stopAdvertising(getAdvertiseCallback());
    }
    catch (IllegalStateException e) {
        LogManager.w(TAG, "Bluetooth is turned off. Transmitter stop call failed.");
    }
    mStarted = false;
}
 
Example 5
/**
 * Tells the <code>BeaconService</code> to start looking for beacons that match the passed
 * <code>Region</code> object.  Note that the Region's unique identifier must be retained to
 * later call the stopMonitoringBeaconsInRegion method.
 *
 * @param region
 * @see BeaconManager#setMonitorNotifier(MonitorNotifier)
 * @see BeaconManager#stopMonitoringBeaconsInRegion(Region region)
 * @see MonitorNotifier
 * @see Region
 */
@TargetApi(18)
public void startMonitoringBeaconsInRegion(@NonNull Region region) throws RemoteException {
    if (!isBleAvailableOrSimulated()) {
        LogManager.w(TAG, "Method invocation will be ignored.");
        return;
    }
    if (determineIfCalledFromSeparateScannerProcess()) {
        return;
    }
    if (mScheduledScanJobsEnabled) {
        MonitoringStatus.getInstanceForApplication(mContext).addRegion(region, new Callback(callbackPackageName()));
    }
    applyChangesToServices(BeaconService.MSG_START_MONITORING, region);

    if (isScannerInDifferentProcess()) {
        MonitoringStatus.getInstanceForApplication(mContext).addLocalRegion(region);
    }
    this.requestStateForRegion(region);
}
 
Example 6
Source Project: android-beacon-library   File: ScanJob.java    License: Apache License 2.0 6 votes vote down vote up
private boolean initialzeScanHelper() {
    mScanState = ScanState.restore(ScanJob.this);
    if (mScanState != null) {
        ScanHelper scanHelper = new ScanHelper(this);
        mScanState.setLastScanStartTimeMillis(System.currentTimeMillis());
        scanHelper.setMonitoringStatus(mScanState.getMonitoringStatus());
        scanHelper.setRangedRegionState(mScanState.getRangedRegionState());
        scanHelper.setBeaconParsers(mScanState.getBeaconParsers());
        scanHelper.setExtraDataBeaconTracker(mScanState.getExtraBeaconDataTracker());
        if (scanHelper.getCycledScanner() == null) {
            try {
                scanHelper.createCycledLeScanner(mScanState.getBackgroundMode(), null);
            }
            catch (OutOfMemoryError e) {
                LogManager.w(TAG, "Failed to create CycledLeScanner thread.");
                return false;
            }
        }
        mScanHelper = scanHelper;
    }
    else {
        return false;
    }
    return true;
}
 
Example 7
/**
 * 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.
 *
 * @param enabled
 */

public void setEnableScheduledScanJobs(boolean enabled) {
    if (isAnyConsumerBound()) {
        LogManager.e(TAG, "ScanJob may not be configured because a consumer is" +
                " already bound.");
        throw new IllegalStateException("Method must be called before calling bind()");
    }
    if (enabled && android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        LogManager.e(TAG, "ScanJob may not be configured because JobScheduler is not" +
                " availble prior to Android 5.0");
        return;
    }
    if (!enabled && android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        LogManager.w(TAG, "Disabling ScanJobs on Android 8+ may disable delivery of "+
                "beacon callbacks in the background unless a foreground service is active.");
    }
    if(!enabled && android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        ScanJobScheduler.getInstance().cancelSchedule(mContext);
    }
    mScheduledScanJobsEnabled = enabled;
}
 
Example 8
/**
 * Tells the <code>BeaconService</code> to stop looking for beacons that match the passed
 * <code>Region</code> object and providing mDistance information for them.
 *
 * @param region
 * @see #setMonitorNotifier(MonitorNotifier notifier)
 * @see #startMonitoringBeaconsInRegion(Region region)
 * @see MonitorNotifier
 * @see Region
 */
@TargetApi(18)
public void stopRangingBeaconsInRegion(@NonNull Region region) throws RemoteException {
    if (!isBleAvailableOrSimulated()) {
        LogManager.w(TAG, "Method invocation will be ignored.");
        return;
    }
    if (determineIfCalledFromSeparateScannerProcess()) {
        return;
    }
    synchronized (rangedRegions) {
        Region regionToRemove = null;
        for (Region rangedRegion : rangedRegions) {
            if (region.getUniqueId().equals(rangedRegion.getUniqueId())) {
                regionToRemove = rangedRegion;
            }
        }
        rangedRegions.remove(regionToRemove);
    }
    applyChangesToServices(BeaconService.MSG_STOP_RANGING, region);
}
 
Example 9
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private BluetoothLeAdvertiser getAdvertiserSafely(BluetoothAdapter adapter) {
    try {
        // This can sometimes throw a NullPointerException as reported here:
        // https://github.com/AltBeacon/android-beacon-library/issues/672
        return adapter.getBluetoothLeAdvertiser();
    }
    catch (Exception e) {
        LogManager.w(TAG, "Cannot get bluetoothLeAdvertiser", e);
    }
    return null;
}
 
Example 10
/**
 * Tells the <code>BeaconService</code> to start looking for beacons that match the passed
 * <code>Region</code> object, and providing updates on the estimated mDistance every seconds while
 * beacons in the Region are visible.  Note that the Region's unique identifier must be retained to
 * later call the stopRangingBeaconsInRegion method.
 *
 * @param region
 * @see BeaconManager#setRangeNotifier(RangeNotifier)
 * @see BeaconManager#stopRangingBeaconsInRegion(Region region)
 * @see RangeNotifier
 * @see Region
 */
@TargetApi(18)
public void startRangingBeaconsInRegion(@NonNull Region region) throws RemoteException {
    if (!isBleAvailableOrSimulated()) {
        LogManager.w(TAG, "Method invocation will be ignored.");
        return;
    }
    if (determineIfCalledFromSeparateScannerProcess()) {
        return;
    }
    synchronized (rangedRegions) {
        rangedRegions.add(region);
    }
    applyChangesToServices(BeaconService.MSG_START_RANGING, region);
}
 
Example 11
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void requestModelMapFromWeb() {

    if (mContext.checkCallingOrSelfPermission("android.permission.INTERNET") != PackageManager.PERMISSION_GRANTED) {
        LogManager.w(TAG, "App has no android.permission.INTERNET permission.  Cannot check for distance model updates");
        return;
    }

    new ModelSpecificDistanceUpdater(mContext, mRemoteUpdateUrlString,
            new ModelSpecificDistanceUpdater.CompletionHandler() {
        @Override
        public void onComplete(String body, Exception ex, int code) {
            if (ex != null) {
                LogManager.w(TAG, "Cannot updated distance models from online database at %s",
                        ex, mRemoteUpdateUrlString);
            }
            else if (code != 200) {
                LogManager.w(TAG, "Cannot updated distance models from online database at %s "
                        + "due to HTTP status code %s", mRemoteUpdateUrlString, code);
            }
            else {
                LogManager.d(TAG,
                        "Successfully downloaded distance models from online database");
                try {
                    buildModelMapWithLock(body);
                    if (saveJson(body)) {
                        loadModelMapFromFile();
                        mDistanceCalculator = findCalculatorForModelWithLock(mRequestedModel);
                        LogManager.i(TAG, "Successfully updated distance model with latest from online database");
                    }
                } catch (JSONException e) {
                    LogManager.w(e, TAG, "Cannot parse json from downloaded distance model");
                }
            }
        }
    }).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
 
Example 12
/**
 * Binds an Android <code>Activity</code> or <code>Service</code> to the <code>BeaconService</code>.  The
 * <code>Activity</code> or <code>Service</code> must implement the <code>beaconConsumer</code> interface so
 * that it can get a callback when the service is ready to use.
 *
 * @param consumer the <code>Activity</code> or <code>Service</code> that will receive the callback when the service is ready.
 */
public void bind(@NonNull BeaconConsumer consumer) {
    if (!isBleAvailableOrSimulated()) {
        LogManager.w(TAG, "Method invocation will be ignored.");
        return;
    }
    synchronized (consumers) {
        ConsumerInfo newConsumerInfo = new ConsumerInfo();
        ConsumerInfo alreadyBoundConsumerInfo = consumers.putIfAbsent(consumer, newConsumerInfo);
        if (alreadyBoundConsumerInfo != null) {
            LogManager.d(TAG, "This consumer is already bound");
        }
        else {
            LogManager.d(TAG, "This consumer is not bound.  Binding now: %s", consumer);
            if (mScheduledScanJobsEnabled) {
                LogManager.d(TAG, "Not starting beacon scanning service. Using scheduled jobs");
                consumer.onBeaconServiceConnect();
            }
            else {
                LogManager.d(TAG, "Binding to service");
                Intent intent = new Intent(consumer.getApplicationContext(), BeaconService.class);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O &&
                        this.getForegroundServiceNotification() != null) {
                    if (isAnyConsumerBound()) {
                        LogManager.i(TAG, "Not starting foreground beacon scanning" +
                                " service.  A consumer is already bound, so it should be started");
                    }
                    else {
                        LogManager.i(TAG, "Starting foreground beacon scanning service.");
                        mContext.startForegroundService(intent);
                    }
                }
                else {
                }
                consumer.bindService(intent, newConsumerInfo.beaconServiceConnection, Context.BIND_AUTO_CREATE);
            }
            LogManager.d(TAG, "consumer count is now: %s", consumers.size());
        }
    }
}
 
Example 13
private void finishRecovery() {
    LogManager.w(TAG, "Recovery attempt finished");
    synchronized(distinctBluetoothAddresses) {
        distinctBluetoothAddresses.clear();
    }
    recoveryInProgress = false;
}
 
Example 14
private DistanceCalculator findCalculatorForModel(AndroidModel model) {
    LogManager.d(TAG, "Finding best distance calculator for %s, %s, %s, %s",
            model.getVersion(), model.getBuildNumber(), model.getModel(),
            model.getManufacturer());

    if (mModelMap == null) {
        LogManager.d(TAG, "Cannot get distance calculator because modelMap was never initialized");
        return null;
    }

    int highestScore = 0;
    AndroidModel bestMatchingModel = null;
    for (AndroidModel candidateModel : mModelMap.keySet()) {
        if (candidateModel.matchScore(model) > highestScore) {
            highestScore = candidateModel.matchScore(model);
            bestMatchingModel = candidateModel;
        }
    }
    if (bestMatchingModel != null) {
        LogManager.d(TAG, "found a match with score %s", highestScore);
        LogManager.d(TAG, "Finding best distance calculator for %s, %s, %s, %s",
                bestMatchingModel.getVersion(), bestMatchingModel.getBuildNumber(),
                bestMatchingModel.getModel(), bestMatchingModel.getManufacturer());
        mModel = bestMatchingModel;
    } else {
        mModel = mDefaultModel;
        LogManager.w(TAG, "Cannot find match for this device.  Using default");
    }
    return mModelMap.get(mModel);
}
 
Example 15
/**
 * Sets the duration in milliseconds spent not scanning between each Bluetooth LE scan cycle when no ranging/monitoring clients are in the foreground
 *
 * @param p
 */
public void setBackgroundBetweenScanPeriod(long p) {
    backgroundBetweenScanPeriod = p;
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O &&
            backgroundBetweenScanPeriod < 15*60*1000 /* 15 min */) {
        LogManager.w(TAG, "Setting a short backgroundBetweenScanPeriod has no effect on "+
                "Android 8+, which is limited to scanning every ~15 minutes");
    }
}
 
Example 16
@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.");
    }
 }
 
Example 17
@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();
}
 
Example 18
Source Project: android-beacon-library   File: ScanJob.java    License: Apache License 2.0 5 votes vote down vote up
private boolean restartScanning() {
    if (mScanState != null && mScanHelper != null) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            mScanHelper.stopAndroidOBackgroundScan();
        }
        long scanPeriod = mScanState.getBackgroundMode() ? mScanState.getBackgroundScanPeriod() : mScanState.getForegroundScanPeriod();
        long betweenScanPeriod = mScanState.getBackgroundMode() ? mScanState.getBackgroundBetweenScanPeriod() : mScanState.getForegroundBetweenScanPeriod();
        if (mScanHelper.getCycledScanner() != null) {
            mScanHelper.getCycledScanner().setScanPeriods(scanPeriod,
                    betweenScanPeriod,
                    mScanState.getBackgroundMode());
        }
        mInitialized = true;
        if (scanPeriod <= 0) {
            LogManager.w(TAG, "Starting scan with scan period of zero.  Exiting ScanJob.");
            if (mScanHelper.getCycledScanner() != null) {
                mScanHelper.getCycledScanner().stop();
            }
            return false;
        }

        if (mScanHelper.getRangedRegionState().size() > 0 || mScanHelper.getMonitoringStatus().regions().size() > 0) {
            if (mScanHelper.getCycledScanner() != null) {
                mScanHelper.getCycledScanner().start();
            }
            return true;
        }
        else {
            if (mScanHelper.getCycledScanner() != null) {
                mScanHelper.getCycledScanner().stop();
            }
            return false;
        }
    }
    else {
        return false;
    }
}
 
Example 19
@Override
public double calculateDistance(int txPower, double rssi) {
    if (mDistanceCalculator == null) {
        LogManager.w(TAG, "distance calculator has not been set");
        return -1.0;
    }
    return mDistanceCalculator.calculateDistance(txPower, rssi);
}
 
Example 20
/**
 * 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.
 *
 * @param backgroundMode true indicates the app is in the background
 * @see #DEFAULT_FOREGROUND_SCAN_PERIOD
 * @see #DEFAULT_FOREGROUND_BETWEEN_SCAN_PERIOD;
 * @see #DEFAULT_BACKGROUND_SCAN_PERIOD;
 * @see #DEFAULT_BACKGROUND_BETWEEN_SCAN_PERIOD;
 * @see #setForegroundScanPeriod(long p)
 * @see #setForegroundBetweenScanPeriod(long p)
 * @see #setBackgroundScanPeriod(long p)
 * @see #setBackgroundBetweenScanPeriod(long p)
 */
public void setBackgroundMode(boolean backgroundMode) {
    if (!isBleAvailableOrSimulated()) {
        LogManager.w(TAG, "Method invocation will be ignored.");
        return;
    }
    mBackgroundModeUninitialized = false;
    if (backgroundMode != mBackgroundMode) {
        mBackgroundMode = backgroundMode;
        try {
            this.updateScanPeriods();
        } catch (RemoteException e) {
            LogManager.e(TAG, "Cannot contact service to set scan periods");
        }
    }
}