Java Code Examples for org.altbeacon.beacon.logging.LogManager

The following examples show how to use org.altbeacon.beacon.logging.LogManager. 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
Source Project: android-beacon-library   Source File: GattBeaconTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDetectsGattBeacon2WithShortIdentifier() {
    org.robolectric.shadows.ShadowLog.stream = System.err;
    LogManager.setLogger(Loggers.verboseLogger());
    LogManager.setVerboseLoggingEnabled(true);
    LogManager.d("GattBeaconTest", "Parsing short packet");
    byte[] bytes = hexStringToByteArray("020106030334121516341210ec007261646975736e6574776f726b7307000000000000000000000000000000000000000000000000000000000000000000");
    BeaconParser parser = new BeaconParser().setBeaconLayout("s:0-1=1234,m:2-2=10,p:3-3:-41,i:4-20v");
    Beacon gattBeacon = parser.fromScanData(bytes, -55, null, 123456L);
    assertNotNull("GattBeacon should be not null if parsed successfully", gattBeacon);
    assertEquals("GattBeacon identifier length should be adjusted smaller if packet is short",
                 16,
                 gattBeacon.getId1().toByteArray().length);
    assertEquals("GattBeacon identifier should have proper first byte",
            (byte)0x00,
            gattBeacon.getId1().toByteArray()[0]);
    assertEquals("GattBeacon identifier should have proper second to last byte",
            (byte) 0x73,
            gattBeacon.getId1().toByteArray()[14]);
    assertEquals("GattBeacon identifier should have proper last byte",
            (byte)0x07,
            gattBeacon.getId1().toByteArray()[15]);

}
 
Example 2
Source Project: android-beacon-library   Source File: BeaconManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 3
public void crashDetected() {
    if (android.os.Build.VERSION.SDK_INT < 18) {
        LogManager.d(TAG, "Ignoring crashes before API 18, because BLE is unsupported.");
        return;
    }
    LogManager.w(TAG, "BluetoothService crash detected");
    if (distinctBluetoothAddresses.size() > 0) {
        LogManager.d(TAG, "Distinct Bluetooth devices seen at crash: %s",
                distinctBluetoothAddresses.size());
    }
    long nowTimestamp = SystemClock.elapsedRealtime();
    lastBluetoothCrashDetectionTime = nowTimestamp;
    detectedCrashCount++;

    if (recoveryInProgress) {
        LogManager.d(TAG, "Ignoring Bluetooth crash because recovery is already in progress.");
    }
    else {
        startRecovery();
    }
    processStateChange();

}
 
Example 4
private BluetoothLeScanner getScanner() {
    try {
        if (mScanner == null) {
            LogManager.d(TAG, "Making new Android L scanner");
            BluetoothAdapter bluetoothAdapter = getBluetoothAdapter();
            if (bluetoothAdapter != null) {
                mScanner = getBluetoothAdapter().getBluetoothLeScanner();
            }
            if (mScanner == null) {
                LogManager.w(TAG, "Failed to make new Android L scanner");
            }
        }
    }
    catch (SecurityException e) {
        LogManager.w(TAG, "SecurityException making new Android L scanner");
    }
    return mScanner;
}
 
Example 5
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 6
Source Project: android-beacon-library   Source File: BluetoothTestJob.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the job id to be used to schedule this job.  This may be set in the
 * AndroidManifest.xml or in single process applications by using #setOverrideJobId
 * @param context
 * @return
 */
public static int getJobId(Context context) {
    if (sOverrideJobId >= 0) {
        LogManager.i(TAG, "Using BluetoothTestJob JobId from static override: "+
                sOverrideJobId);
        return sOverrideJobId;
    }
    PackageItemInfo info = null;
    try {
        info = context.getPackageManager().getServiceInfo(new ComponentName(context,
                BluetoothTestJob.class), PackageManager.GET_META_DATA);
    } catch (PackageManager.NameNotFoundException e) { /* do nothing here */ }
    if (info != null && info.metaData != null && info.metaData.get("jobId") != null) {
        int jobId = info.metaData.getInt("jobId");
        LogManager.i(TAG, "Using BluetoothTestJob JobId from manifest: "+jobId);
        return jobId;
    }
    else {
        throw new RuntimeException("Cannot get job id from manifest.  " +
                "Make sure that the BluetoothTestJob is configured in the manifest.");
    }
}
 
Example 7
/**
 * Calculated the estimated distance in meters to the beacon based on a reference rssi at 1m
 * and the known actual rssi at the current location
 *
 * @param txPower
 * @param rssi
 * @return estimated distance
 */
@Override
public double calculateDistance(int txPower, double rssi) {
    if (rssi == 0) {
        return -1.0; // if we cannot determine accuracy, return -1.
    }

    LogManager.d(TAG, "calculating distance based on mRssi of %s and txPower of %s", rssi, txPower);


    double ratio = rssi*1.0/txPower;
    double distance;
    if (ratio < 1.0) {
        distance =  Math.pow(ratio,10);
    }
    else {
        distance =  (mCoefficient1)*Math.pow(ratio,mCoefficient2) + mCoefficient3;
    }
    LogManager.d(TAG, "avg mRssi: %s distance: %s", rssi, distance);
    return distance;
}
 
Example 8
Source Project: android-beacon-library   Source File: RegionBootstrap.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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");
}
 
Example 9
Source Project: android-beacon-library   Source File: RegionBootstrap.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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");
}
 
Example 10
Source Project: android-beacon-library   Source File: RegionBootstrap.java    License: 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 11
Source Project: android-beacon-library   Source File: BeaconManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 12
Source Project: android-beacon-library   Source File: CycledLeScanner.java    License: Apache License 2.0 6 votes vote down vote up
@MainThread
protected void scheduleScanCycleStop() {
    // Stops scanning after a pre-defined scan period.
    long millisecondsUntilStop = mScanCycleStopTime - SystemClock.elapsedRealtime();
    if (mScanningEnabled && millisecondsUntilStop > 0) {
        LogManager.d(TAG, "Waiting to stop scan cycle for another %s milliseconds",
                millisecondsUntilStop);
        if (mBackgroundFlag) {
            setWakeUpAlarm();
        }
        mHandler.postDelayed(new Runnable() {
            @MainThread
            @Override
            public void run() {
                scheduleScanCycleStop();
            }
        }, millisecondsUntilStop > 1000 ? 1000 : millisecondsUntilStop);
    } else {
        finishScanCycle();
    }
}
 
Example 13
Source Project: android-beacon-library   Source File: ScanJobScheduler.java    License: Apache License 2.0 6 votes vote down vote up
public void scheduleAfterBackgroundWakeup(Context context, List<ScanResult> scanResults) {
    if (scanResults != null) {
        mBackgroundScanResultQueue.addAll(scanResults);
    }
    synchronized (this) {
        // We typically get a bunch of calls in a row here, separated by a few millis.  Only do this once.
        if (System.currentTimeMillis() - mScanJobScheduleTime > MIN_MILLIS_BETWEEN_SCAN_JOB_SCHEDULING) {
            LogManager.d(TAG, "scheduling an immediate scan job because last did "+(System.currentTimeMillis() - mScanJobScheduleTime)+"millis ago.");
            mScanJobScheduleTime = System.currentTimeMillis();
        }
        else {
            LogManager.d(TAG, "Not scheduling an immediate scan job because we just did recently.");
            return;
        }
    }
    ScanState scanState = ScanState.restore(context);
    schedule(context, scanState, true);
}
 
Example 14
Source Project: android-beacon-library   Source File: ScanJob.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean onStopJob(JobParameters params) {
    // See corresponding synchronized block in onStartJob
    synchronized(ScanJob.this) {
        mStopCalled = true;
        if (params.getJobId() == getPeriodicScanJobId(this)) {
            LogManager.i(TAG, "onStopJob called for periodic scan " + this);
        }
        else {
            LogManager.i(TAG, "onStopJob called for immediate scan " + this);
        }
        LogManager.d(TAG, "ScanJob Lifecycle STOP: "+ScanJob.this);
        // Cancel the stop timer.  The OS is stopping prematurely
        mStopHandler.removeCallbacksAndMessages(null);

        stopScanning();
        startPassiveScanIfNeeded();
        if (mScanHelper != null) {
            mScanHelper.terminateThreads();
        }
    }
    return false;
}
 
Example 15
Source Project: android-beacon-library   Source 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 16
Source Project: android-beacon-library   Source File: GattBeaconTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDetectsGattBeacon() {
    org.robolectric.shadows.ShadowLog.stream = System.err;
    LogManager.setLogger(Loggers.verboseLogger());
    LogManager.setVerboseLoggingEnabled(true);
    System.err.println("verbose logging:"+LogManager.isVerboseLoggingEnabled());
    byte[] bytes = hexStringToByteArray("020106030334121516341200e72f234454f4911ba9ffa6000000000001000000000000000000000000000000000000000000000000000000000000000000");
    BeaconParser parser = new BeaconParser().setBeaconLayout("s:0-1=1234,m:2-2=00,p:3-3:-41,i:4-13,i:14-19");
    assertNotNull("Service uuid parsed should not be null", parser.getServiceUuid());
    Beacon gattBeacon = parser.fromScanData(bytes, -55, null, 123456L);
    assertNotNull("GattBeacon should be not null if parsed successfully", gattBeacon);
    assertEquals("id1 should be parsed", "0x2f234454f4911ba9ffa6", gattBeacon.getId1().toString());
    assertEquals("id2 should be parsed", "0x000000000001", gattBeacon.getId2().toString());
    assertEquals("serviceUuid should be parsed", 0x1234, gattBeacon.getServiceUuid());
    assertEquals("txPower should be parsed", -66, gattBeacon.getTxPower());
}
 
Example 17
Source Project: android-beacon-library   Source File: CycledLeScanner.java    License: Apache License 2.0 6 votes vote down vote up
@MainThread
public void stop() {
    LogManager.d(TAG, "stop called");
    mScanningEnabled = false;
    if (mScanCyclerStarted) {
        scanLeDevice(false);
        // If we have left scanning on between scan periods, now is the time to shut it off.
        if (mScanningLeftOn) {
            LogManager.d(TAG, "Stopping scanning previously left on.");
            mScanningLeftOn = false;
            try {
                LogManager.d(TAG, "stopping bluetooth le scan");
                finishScan();
            } catch (Exception e) {
                LogManager.w(e, TAG, "Internal Android exception scanning for beacons");
            }
        }
    } else {
        LogManager.d(TAG, "scanning already stopped");
    }
}
 
Example 18
Source Project: android-beacon-library   Source File: BeaconParserTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testParsesBeaconMissingDataField() {
    LogManager.setLogger(Loggers.verboseLogger());
    org.robolectric.shadows.ShadowLog.stream = System.err;
    byte[] bytes = hexStringToByteArray("02011a1aff1801beac2f234454cf6d4a0fadf2f4911ba9ffa600010002c5000000");
    BeaconParser parser = new BeaconParser();
    parser.setBeaconLayout("m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25");
    Beacon beacon = parser.fromScanData(bytes, -55, null, 123456L);
    assertEquals("mRssi should be as passed in", -55, beacon.getRssi());
    assertEquals("uuid should be parsed", "2f234454-cf6d-4a0f-adf2-f4911ba9ffa6", beacon.getIdentifier(0).toString());
    assertEquals("id2 should be parsed", "1", beacon.getIdentifier(1).toString());
    assertEquals("id3 should be parsed", "2", beacon.getIdentifier(2).toString());
    assertEquals("txPower should be parsed", -59, beacon.getTxPower());
    assertEquals("manufacturer should be parsed", 0x118 ,beacon.getManufacturer());
    assertEquals("missing data field zero should be zero", new Long(0l), beacon.getDataFields().get(0));

}
 
Example 19
Source Project: android-beacon-library   Source File: AndroidModel.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Calculates a qualitative match score between two different Android device models for the
 * purposes of how likely they are to have similar Bluetooth signal level responses
 * @param otherModel
 * @return match quality, higher numbers are a better match
 */
public int matchScore(AndroidModel otherModel) {
    int score = 0;
    if (this.mManufacturer.equalsIgnoreCase(otherModel.mManufacturer)) {
        score = 1;
    }
    if (score ==1 && this.mModel.equals(otherModel.mModel)) {
        score = 2;
    }
    if (score == 2 && this.mBuildNumber.equals(otherModel.mBuildNumber)) {
        score = 3;
    }
    if (score == 3 && this.mVersion.equals(otherModel.mVersion)) {
        score = 4;
    }
    LogManager.d(TAG, "Score is %s for %s compared to %s", score, toString(), otherModel);
    return score;
}
 
Example 20
Source Project: android-beacon-library   Source File: CycledLeScanner.java    License: Apache License 2.0 6 votes vote down vote up
@MainThread
public void destroy() {
    LogManager.d(TAG, "Destroying");

    // Remove any postDelayed Runnables queued for the next scan cycle
    mHandler.removeCallbacksAndMessages(null);
    // We cannot quit the thread used by the handler until queued Runnables have been processed,
    // because the handler is what stops scanning, and we do not want scanning left on.
    // So we stop the thread using the handler, so we make sure it happens after all other
    // waiting Runnables are finished.
    mScanHandler.post(new Runnable() {
        @WorkerThread
        @Override
        public void run() {
            LogManager.d(TAG, "Quitting scan thread");
            mScanThread.quit();
        }
    });
    cleanupCancelAlarmOnUserSwitch();
}
 
Example 21
Source Project: android-beacon-library   Source File: ScanState.java    License: Apache License 2.0 6 votes vote down vote up
public int getScanJobRuntimeMillis() {
    long scanPeriodMillis;
    LogManager.d(TAG, "ScanState says background mode for ScanJob is "+getBackgroundMode());
    if (getBackgroundMode()) {
        scanPeriodMillis = getBackgroundScanPeriod();
    }
    else {
        scanPeriodMillis = getForegroundScanPeriod();
    }
    if (!getBackgroundMode()) {
        // if we are in the foreground, we keep the scan job going for the minimum interval
        if (scanPeriodMillis < MIN_SCAN_JOB_INTERVAL_MILLIS) {
            return MIN_SCAN_JOB_INTERVAL_MILLIS;
        }
    }
    return (int) scanPeriodMillis;
}
 
Example 22
@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 23
Source Project: android-beacon-library   Source File: RangedBeacon.java    License: Apache License 2.0 6 votes vote down vote up
public void commitMeasurements() {
     if (!getFilter().noMeasurementsAvailable()) {
         double runningAverage = getFilter().calculateRssi();
         mBeacon.setRunningAverageRssi(runningAverage);
         mBeacon.setRssiMeasurementCount(getFilter().getMeasurementCount());
         LogManager.d(TAG, "calculated new runningAverageRssi: %s", runningAverage);
    }
    else {
        LogManager.d(TAG, "No measurements available to calculate running average");
    }
    mBeacon.setPacketCount(packetCount);
    mBeacon.setFirstCycleDetectionTimestamp(firstCycleDetectionTimestamp);
    mBeacon.setLastCycleDetectionTimestamp(lastCycleDetectionTimestamp);
    packetCount = 0;
    firstCycleDetectionTimestamp = 0L;
    lastCycleDetectionTimestamp = 0L;
}
 
Example 24
Source Project: android-beacon-library   Source File: BeaconManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 25
Source Project: beaconloc   Source File: BackgroundSwitchWatcher.java    License: Apache License 2.0 5 votes vote down vote up
/**
     * Constructs a new BackgroundSwitchWatcher
     *
     * @param context
     */
public BackgroundSwitchWatcher(Context context) {
        if (android.os.Build.VERSION.SDK_INT < 18) {
            LogManager.w(TAG, "BackgroundSwitchWatcher requires API 18 or higher.");
        }
        mContext = context;
        ((Application)context.getApplicationContext()).registerActivityLifecycleCallbacks(this);
    }
 
Example 26
Source Project: beaconloc   Source File: BackgroundSwitchWatcher.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onActivityStarted(Activity activity) {
    activeActivityCount++;
    LogManager.d(TAG, "activity started: %s active activities: %s", activity, activeActivityCount);

    if (activeActivityCount == 1) {
        BeaconLocatorApp.from(mContext).enableBackgroundScan(false);
    }
}
 
Example 27
Source Project: beaconloc   Source File: BackgroundSwitchWatcher.java    License: 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 28
Source Project: android-beacon-library   Source File: BluetoothMedic.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * If set to true, bluetooth will be power cycled on any tests run that determine bluetooth is
 * in a bad state.
 *
 * @param context
 */
@SuppressWarnings("unused")
@RequiresApi(21)
public void enablePowerCycleOnFailures(Context context) {
    initializeWithContext(context);
    if (this.mLocalBroadcastManager != null) {
        this.mLocalBroadcastManager.registerReceiver(this.mBluetoothEventReceiver,
                new IntentFilter("onScanFailed"));
        this.mLocalBroadcastManager.registerReceiver(this.mBluetoothEventReceiver,
                new IntentFilter("onStartFailure"));
        LogManager.d(TAG,
                "Medic monitoring for transmission and scan failure notifications with receiver: "
                        + this.mBluetoothEventReceiver);
    }
}
 
Example 29
@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 30
Source Project: android-beacon-library   Source File: Stats.java    License: Apache License 2.0 5 votes vote down vote up
private void logSample(Sample sample, boolean showHeader) {
    if (showHeader) {
        LogManager.d(TAG, "sample start time, sample stop time, first detection" +
                " time, last detection time, max millis between detections, detection count");
    }
    LogManager.d(TAG, "%s, %s, %s, %s, %s, %s",
            formattedDate(sample.sampleStartTime), formattedDate(sample.sampleStopTime),
            formattedDate(sample.firstDetectionTime), formattedDate(sample.lastDetectionTime),
            sample.maxMillisBetweenDetections, sample.detectionCount);
}