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

The following examples show how to use org.altbeacon.beacon.logging.LogManager#d() . 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
Source File: CycledLeScanner.java    From android-beacon-library with Apache License 2.0 6 votes vote down vote up
private long getNextScanStartTime() {
    // Because many apps may use this library on the same device, we want to try to synchronize
    // scanning as much as possible in order to save battery.  Therefore, we will set the scan
    // intervals to be on a predictable interval using a modulus of the system time.  This may
    // cause scans to start a little earlier than otherwise, but it should be acceptable.
    // This way, if multiple apps on the device are using the default scan periods, then they
    // will all be doing scans at the same time, thereby saving battery when none are scanning.
    // This, of course, won't help at all if people set custom scan periods.  But since most
    // people accept the defaults, this will likely have a positive effect.
    if (mBetweenScanPeriod == 0) {
        return SystemClock.elapsedRealtime();
    }
    long fullScanCycle = mScanPeriod + mBetweenScanPeriod;
    long normalizedBetweenScanPeriod = mBetweenScanPeriod-(SystemClock.elapsedRealtime() % fullScanCycle);
    LogManager.d(TAG, "Normalizing between scan period from %s to %s", mBetweenScanPeriod,
            normalizedBetweenScanPeriod);

    return SystemClock.elapsedRealtime()+normalizedBetweenScanPeriod;
}
 
Example 2
Source File: RunningAverageRssiFilter.java    From android-beacon-library with Apache License 2.0 6 votes vote down vote up
@Override
public double calculateRssi() {
    refreshMeasurements();
    int size = mMeasurements.size();
    int startIndex = 0;
    int endIndex = size -1;
    if (size > 2) {
        startIndex = size/10+1;
        endIndex = size-size/10-2;
    }

    double sum = 0;
    for (int i = startIndex; i <= endIndex; i++) {
        sum += mMeasurements.get(i).rssi;
    }
    double runningAverage = sum/(endIndex-startIndex+1);

    LogManager.d(TAG, "Running average mRssi based on %s measurements: %s",
            size, runningAverage);
    return runningAverage;
}
 
Example 3
Source File: RegionBootstrap.java    From android-beacon-library with Apache License 2.0 6 votes vote down vote up
/**
 * 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");
}
 
Example 4
Source File: BeaconManager.java    From android-beacon-library with Apache License 2.0 6 votes vote down vote up
public void onServiceConnected(ComponentName className, IBinder service) {
    LogManager.d(TAG, "we have a connection to the service now");
    if (mScannerInSameProcess == null) {
        mScannerInSameProcess = false;
    }
    serviceMessenger = new Messenger(service);
    // This will sync settings to the scanning service if it is in a different process
    applySettings();
    synchronized(consumers) {
        Iterator<Map.Entry<BeaconConsumer, ConsumerInfo>> iter = consumers.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<BeaconConsumer, ConsumerInfo> entry = iter.next();

            if (!entry.getValue().isConnected) {
                entry.getKey().onBeaconServiceConnect();
                entry.getValue().isConnected = true;
            }
        }
    }
}
 
Example 5
Source File: RegionBootstrap.java    From android-beacon-library with Apache License 2.0 6 votes vote down vote up
/**
 * 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");
}
 
Example 6
Source File: CycledLeScanner.java    From android-beacon-library with Apache License 2.0 6 votes vote down vote up
/**
 * On Android N and later, a scan that runs for more than 30 minutes will be automatically
 * stopped by the OS and converted to an "opportunistic" scan, meaning that they will only yield
 * detections if another app is scanning.  This is inteneded to save battery.  This can be
 * prevented by stopping scanning and restarting.  This method returns true if:
 *   * this is Android N or later
 *   * we are close to the 30 minute boundary since the last scan started
 *   * The app developer has explicitly enabled long-running scans
 * @return true if we must stop scanning to prevent
 */
private boolean mustStopScanToPreventAndroidNScanTimeout() {
    long timeOfNextScanCycleEnd = SystemClock.elapsedRealtime() +  mBetweenScanPeriod +
            mScanPeriod;
    boolean timeoutAtRisk = android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.N &&
            mCurrentScanStartTime > 0 &&
            (timeOfNextScanCycleEnd - mCurrentScanStartTime > ANDROID_N_MAX_SCAN_DURATION_MILLIS);

    if (timeoutAtRisk) {
        LogManager.d(TAG, "The next scan cycle would go over the Android N max duration.");
        if  (mLongScanForcingEnabled) {
            LogManager.d(TAG, "Stopping scan to prevent Android N scan timeout.");
            return true;
        }
        else {
            LogManager.w(TAG, "Allowing a long running scan to be stopped by the OS.  To " +
                    "prevent this, set longScanForcingEnabled in the AndroidBeaconLibrary.");
        }
    }
    return false;
}
 
Example 7
Source File: BeaconTransmitter.java    From android-beacon-library with Apache License 2.0 6 votes vote down vote up
/**
 * 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 8
Source File: BackgroundSwitchWatcher.java    From beaconloc with Apache License 2.0 5 votes vote down vote up
@Override
public void onActivityStopped(Activity activity) {
    activeActivityCount--;
    LogManager.d(TAG,"activity stopped: %s active activities: %s", activity, activeActivityCount);
    if (activeActivityCount <= 0) {
        BeaconLocatorApp.from(mContext).enableBackgroundScan(true);
    }
}
 
Example 9
Source File: BackgroundPowerSaver.java    From android-beacon-library with Apache License 2.0 5 votes vote down vote up
@Override
public void onActivityResumed(Activity activity) {
    activeActivityCount++;
    if (activeActivityCount < 1) {
        LogManager.d(TAG, "reset active activity count on resume.  It was %s", activeActivityCount);
        activeActivityCount = 1;
    }
    beaconManager.setBackgroundMode(false);
    LogManager.d(TAG, "activity resumed: %s active activities: %s", activity, activeActivityCount);
}
 
Example 10
Source File: ScanJobScheduler.java    From android-beacon-library with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 11
Source File: BackgroundPowerSaver.java    From android-beacon-library with Apache License 2.0 5 votes vote down vote up
@Override
public void onActivityPaused(Activity activity) {
    activeActivityCount--;
    LogManager.d(
            TAG,
            "activity paused: %s active activities: %s",
            activity,
            activeActivityCount
    );
    if (activeActivityCount < 1) {
        LogManager.d(TAG, "setting background mode");
        beaconManager.setBackgroundMode(true);
    }
}
 
Example 12
Source File: AltBeaconParserTest.java    From android-beacon-library with Apache License 2.0 5 votes vote down vote up
@Test
public void testParseWrongFormatReturnsNothing() {
    BeaconManager.setDebug(true);
    org.robolectric.shadows.ShadowLog.stream = System.err;
    LogManager.d("XXX", "testParseWrongFormatReturnsNothing start");
    byte[] bytes = hexStringToByteArray("02011a1aff1801ffff2f234454cf6d4a0fadf2f4911ba9ffa600010002c509");
    AltBeaconParser parser = new AltBeaconParser();
    Beacon beacon = parser.fromScanData(bytes, -55, null, 123456L);
    LogManager.d("XXX", "testParseWrongFormatReturnsNothing end");
    assertNull("Beacon should be null if not parsed successfully", beacon);
}
 
Example 13
Source File: Stats.java    From android-beacon-library with Apache License 2.0 5 votes vote down vote up
private void logSamples() {
    LogManager.d(TAG, "--- Stats for %s samples", mSamples.size());
    boolean firstPass = true;
    for (Sample sample : mSamples) {
        logSample(sample, firstPass);
        firstPass = false;
    }
}
 
Example 14
Source File: MonitoringStatus.java    From android-beacon-library with Apache License 2.0 5 votes vote down vote up
private List<Region> regionsMatchingTo(Beacon beacon) {
    List<Region> matched = new ArrayList<Region>();
    for (Region region : regions()) {
        if (region.matchesBeacon(beacon)) {
            matched.add(region);
        } else {
            LogManager.d(TAG, "This region (%s) does not match beacon: %s", region, beacon);
        }
    }
    return matched;
}
 
Example 15
Source File: RangeState.java    From android-beacon-library with Apache License 2.0 5 votes vote down vote up
public void addBeacon(Beacon beacon) {
    RangedBeacon rangedBeacon = mRangedBeacons.get(beacon);
    if (rangedBeacon != null) {
        if (LogManager.isVerboseLoggingEnabled()) {
            LogManager.d(TAG, "adding %s to existing range for: %s", beacon, rangedBeacon);
        }
        rangedBeacon.updateBeacon(beacon);
    }
    else {
        if (LogManager.isVerboseLoggingEnabled()) {
            LogManager.d(TAG, "adding %s to new rangedBeacon", beacon);
        }
        mRangedBeacons.put(beacon, new RangedBeacon(beacon));
    }
}
 
Example 16
Source File: SettingsData.java    From android-beacon-library with Apache License 2.0 4 votes vote down vote up
public void apply(@NonNull BeaconService scanService) {
    LogManager.d(TAG, "Applying settings changes to scanner in other process");
    BeaconManager beaconManager = BeaconManager.getInstanceForApplication(scanService);
    List<BeaconParser> beaconParsers = beaconManager.getBeaconParsers();
    boolean beaconParsersChanged = false;
    if (beaconParsers.size() == mBeaconParsers.size()) {
        for (int i = 0; i < beaconParsers.size(); i++) {
            if (!beaconParsers.get(i).equals(mBeaconParsers.get(i))) {
                LogManager.d(TAG, "Beacon parsers have changed to: "+mBeaconParsers.get(i).getLayout());
                beaconParsersChanged = true;
                break;
            }
        }
    }
    else {
        beaconParsersChanged = true;
        LogManager.d(TAG, "Beacon parsers have been added or removed.");
    }
    if (beaconParsersChanged) {
        LogManager.d(TAG, "Updating beacon parsers");
        beaconManager.getBeaconParsers().clear();
        beaconManager.getBeaconParsers().addAll(mBeaconParsers);
        scanService.reloadParsers();
    }
    else {
        LogManager.d(TAG, "Beacon parsers unchanged.");
    }
    MonitoringStatus monitoringStatus = MonitoringStatus.getInstanceForApplication(scanService);
    if (monitoringStatus.isStatePreservationOn() &&
            !mRegionStatePersistenceEnabled) {
        monitoringStatus.stopStatusPreservation();
    }
    else if (!monitoringStatus.isStatePreservationOn() &&
            mRegionStatePersistenceEnabled) {
        monitoringStatus.startStatusPreservation();
    }
    beaconManager.setAndroidLScanningDisabled(mAndroidLScanningDisabled);
    BeaconManager.setRegionExitPeriod(mRegionExitPeriod);
    RangeState.setUseTrackingCache(mUseTrackingCache);
    Beacon.setHardwareEqualityEnforced(mHardwareEqualityEnforced);
}
 
Example 17
Source File: CycledLeScannerForLollipop.java    From android-beacon-library with Apache License 2.0 4 votes vote down vote up
protected boolean deferScanIfNeeded() {
    // This method is called to see if it is time to start a scan
    long millisecondsUntilStart = mNextScanCycleStartTime - SystemClock.elapsedRealtime();
    final boolean deferScan = millisecondsUntilStart > 0;
    final boolean scanActiveBefore = mMainScanCycleActive;
    mMainScanCycleActive = !deferScan;
    if (deferScan) {
        long secsSinceLastDetection = SystemClock.elapsedRealtime() -
                DetectionTracker.getInstance().getLastDetectionTime();
        // If we have seen a device recently
        // devices should behave like pre-Android L devices, because we don't want to drain battery
        // by continuously delivering packets for beacons visible in the background
        if (scanActiveBefore) {
            if (secsSinceLastDetection > BACKGROUND_L_SCAN_DETECTION_PERIOD_MILLIS) {
                mBackgroundLScanStartTime = SystemClock.elapsedRealtime();
                mBackgroundLScanFirstDetectionTime = 0l;
                LogManager.d(TAG, "This is Android L. Preparing to do a filtered scan for the background.");
                // On Android L, between scan cycles do a scan with a filter looking for any beacon
                // if we see one of those beacons, we need to deliver the results
                // Only scan between cycles if the between can cycle time > 6 seconds.  A shorter low
                // power scan is unlikely to be useful, and might trigger a "scanning too frequently"
                // error on Android N.
                if (mBetweenScanPeriod > 6000l) {
                    startScan();
                }
                else {
                    LogManager.d(TAG, "Suppressing scan between cycles because the between scan cycle is too short.");
                }


            } else {
                // TODO: Consider starting a scan with delivery based on the filters *NOT* being seen
                // This API is now available in Android M
                LogManager.d(TAG, "This is Android L, but we last saw a beacon only %s "
                        + "ago, so we will not keep scanning in background.",
                        secsSinceLastDetection);
            }
        }
        if (mBackgroundLScanStartTime > 0l) {
            // if we are in here, we have detected beacons recently in a background L scan
            if (DetectionTracker.getInstance().getLastDetectionTime() > mBackgroundLScanStartTime) {
                if (mBackgroundLScanFirstDetectionTime == 0l) {
                    mBackgroundLScanFirstDetectionTime = DetectionTracker.getInstance().getLastDetectionTime();
                }
                if (SystemClock.elapsedRealtime() - mBackgroundLScanFirstDetectionTime
                        >= BACKGROUND_L_SCAN_DETECTION_PERIOD_MILLIS) {
                    // if we are in here, it has been more than 10 seconds since we detected
                    // a beacon in background L scanning mode.  We need to stop scanning
                    // so we do not drain battery
                    LogManager.d(TAG, "We've been detecting for a bit.  Stopping Android L background scanning");
                    stopScan();
                    mBackgroundLScanStartTime = 0l;
                }
                else {
                    // report the results up the chain
                    LogManager.d(TAG, "Delivering Android L background scanning results");
                    mCycledLeScanCallback.onCycleEnd();
                }
            }
        }
        LogManager.d(TAG, "Waiting to start full Bluetooth scan for another %s milliseconds",
                millisecondsUntilStart);
        // Don't actually wait until the next scan time -- only wait up to 1 second.  This
        // allows us to start scanning sooner if a consumer enters the foreground and expects
        // results more quickly.
        if (scanActiveBefore && mBackgroundFlag) {
            setWakeUpAlarm();
        }
        mHandler.postDelayed(new Runnable() {
            @MainThread
            @Override
            public void run() {
                scanLeDevice(true);
            }
        }, millisecondsUntilStart > 1000 ? 1000 : millisecondsUntilStart);
    } else {
        if (mBackgroundLScanStartTime > 0l) {
            stopScan();
            mBackgroundLScanStartTime = 0;
        }
    }
    return deferScan;
}
 
Example 18
Source File: CycledLeScannerForLollipop.java    From android-beacon-library with Apache License 2.0 4 votes vote down vote up
@Override
protected void finishScan() {
    LogManager.d(TAG, "Stopping scan");
    stopScan();
    mScanningPaused = true;
}
 
Example 19
Source File: BluetoothCrashResolver.java    From android-beacon-library with Apache License 2.0 4 votes vote down vote up
/**
 * Stops looking for crashes.  Does not need to be called in normal operations, but may be
 * useful for testing.
 */
public void stop() {
    context.unregisterReceiver(receiver);
    LogManager.d(TAG, "stopped listening for BluetoothAdapter events");
    saveState();
}
 
Example 20
Source File: CycledLeScanner.java    From android-beacon-library with Apache License 2.0 4 votes vote down vote up
/**
 * Tells the cycler the scan rate and whether it is in operating in background mode.
 * Background mode flag  is used only with the Android 5.0 scanning implementations to switch
 * between LOW_POWER_MODE vs. LOW_LATENCY_MODE
 * @param backgroundFlag
 */
@MainThread
public void setScanPeriods(long scanPeriod, long betweenScanPeriod, boolean backgroundFlag) {
    LogManager.d(TAG, "Set scan periods called with %s, %s Background mode must have changed.",
            scanPeriod, betweenScanPeriod);
    if (mBackgroundFlag != backgroundFlag) {
        mRestartNeeded = true;
    }
    mBackgroundFlag = backgroundFlag;
    mScanPeriod = scanPeriod;
    mBetweenScanPeriod = betweenScanPeriod;
    if (mBackgroundFlag) {
        LogManager.d(TAG, "We are in the background.  Setting wakeup alarm");
        setWakeUpAlarm();
    } else {
        LogManager.d(TAG, "We are not in the background.  Cancelling wakeup alarm");
        cancelWakeUpAlarm();
    }
    long now = SystemClock.elapsedRealtime();
    if (mNextScanCycleStartTime > now) {
        // We are waiting to start scanning.  We may need to adjust the next start time
        // only do an adjustment if we need to make it happen sooner.  Otherwise, it will
        // take effect on the next cycle.
        long proposedNextScanStartTime = (mLastScanCycleEndTime + betweenScanPeriod);
        if (proposedNextScanStartTime < mNextScanCycleStartTime) {
            mNextScanCycleStartTime = proposedNextScanStartTime;
            LogManager.i(TAG, "Adjusted nextScanStartTime to be %s",
                    new Date(mNextScanCycleStartTime - SystemClock.elapsedRealtime() + System.currentTimeMillis()));
        }
    }
    if (mScanCycleStopTime > now) {
        // we are waiting to stop scanning.  We may need to adjust the stop time
        // only do an adjustment if we need to make it happen sooner.  Otherwise, it will
        // take effect on the next cycle.
        long proposedScanStopTime = (mLastScanCycleStartTime + scanPeriod);
        if (proposedScanStopTime < mScanCycleStopTime) {
            mScanCycleStopTime = proposedScanStopTime;
            LogManager.i(TAG, "Adjusted scanStopTime to be %s", mScanCycleStopTime);
        }
    }
}