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

The following examples show how to use org.altbeacon.beacon.logging.LogManager#i() . 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: BluetoothTestJob.java    From android-beacon-library with 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 2
Source File: ScanJob.java    From android-beacon-library with 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 3
Source File: BeaconService.java    From android-beacon-library with Apache License 2.0 6 votes vote down vote up
@MainThread
@Override
public void onDestroy() {
    LogManager.e(TAG, "onDestroy()");
    if (android.os.Build.VERSION.SDK_INT < 18) {
        LogManager.w(TAG, "Not supported prior to API 18.");
        return;
    }
    if (mBeaconNotificationProcessor != null) {
        mBeaconNotificationProcessor.unregister();
    }
    if (bluetoothCrashResolver != null) {
        bluetoothCrashResolver.stop();
    }
    LogManager.i(TAG, "onDestroy called.  stopping scanning");
    handler.removeCallbacksAndMessages(null);

    if (mScanHelper.getCycledScanner() != null) {
        mScanHelper.getCycledScanner().stop();
        mScanHelper.getCycledScanner().destroy();
    }
    mScanHelper.getMonitoringStatus().stopStatusPreservation();
    mScanHelper.terminateThreads();
}
 
Example 4
Source File: ScanJob.java    From android-beacon-library with Apache License 2.0 6 votes vote down vote up
private static int getJobIdFromManifest(Context context, String name) {
    PackageItemInfo info = null;
    try {
        info = context.getPackageManager().getServiceInfo(new ComponentName(context,
                ScanJob.class), PackageManager.GET_META_DATA);
    } catch (PackageManager.NameNotFoundException e) { /* do nothing here */ }
    if (info != null && info.metaData != null && info.metaData.get(name) != null) {
        int jobId = info.metaData.getInt(name);
        LogManager.i(TAG, "Using "+name+" from manifest: "+jobId);
        return jobId;
    }
    else {
        throw new RuntimeException("Cannot get job id from manifest.  " +
                "Make sure that the "+name+" is configured in the manifest for the ScanJob.");
    }
}
 
Example 5
Source File: BeaconManager.java    From android-beacon-library with Apache License 2.0 5 votes vote down vote up
/**
 * 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 6
Source File: BeaconManager.java    From android-beacon-library with Apache License 2.0 5 votes vote down vote up
protected void checkIfMainProcess() {
    ProcessUtils processUtils = new ProcessUtils(mContext);
    String processName = processUtils.getProcessName();
    String packageName = processUtils.getPackageName();
    int pid = processUtils.getPid();
    mMainProcess = processUtils.isMainProcess();
    LogManager.i(TAG, "BeaconManager started up on pid "+pid+" named '"+processName+"' for application package '"+packageName+"'.  isMainProcess="+mMainProcess);
}
 
Example 7
Source File: CycledLeScanner.java    From android-beacon-library with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example 8
Source File: BeaconService.java    From android-beacon-library with Apache License 2.0 5 votes vote down vote up
/**
 * methods for clients
 */
@MainThread
public void startRangingBeaconsInRegion(Region region, Callback callback) {
    synchronized (mScanHelper.getRangedRegionState()) {
        if (mScanHelper.getRangedRegionState().containsKey(region)) {
            LogManager.i(TAG, "Already ranging that region -- will replace existing region.");
            mScanHelper.getRangedRegionState().remove(region); // need to remove it, otherwise the old object will be retained because they are .equal //FIXME That is not true
        }
        mScanHelper.getRangedRegionState().put(region, new RangeState(callback));
        LogManager.d(TAG, "Currently ranging %s regions.", mScanHelper.getRangedRegionState().size());
    }
    if (mScanHelper.getCycledScanner() != null) {
        mScanHelper.getCycledScanner().start();
    }
}
 
Example 9
Source File: BeaconService.java    From android-beacon-library with Apache License 2.0 5 votes vote down vote up
@Override
public boolean onUnbind(Intent intent) {
    LogManager.i(TAG, "unbinding so destroying self");
    this.stopForeground(true);
    this.stopSelf();
    return false;
}
 
Example 10
Source File: BeaconService.java    From android-beacon-library with Apache License 2.0 5 votes vote down vote up
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    LogManager.i(TAG,
            intent == null ?
                    "starting with null intent"
                    :
                    "starting with intent " + intent.toString()
    );
    return super.onStartCommand(intent, flags, startId);
}
 
Example 11
Source File: ScanJob.java    From android-beacon-library with Apache License 2.0 5 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 the application context
 * @return the job id
 */
public static int getPeriodicScanJobId(Context context) {
    if (sOverrideImmediateScanJobId >= 0) {
        LogManager.i(TAG, "Using PeriodicScanJobId from static override: "+
                sOverridePeriodicScanJobId);
        return sOverridePeriodicScanJobId;
    }
    return getJobIdFromManifest(context, "periodicScanJobId");
}
 
Example 12
Source File: ScanJob.java    From android-beacon-library with Apache License 2.0 5 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 the application context
 * @return the job id
 */
public static int getImmediateScanJobId(Context context) {
    if (sOverrideImmediateScanJobId >= 0) {
        LogManager.i(TAG, "Using ImmediateScanJobId from static override: "+
                sOverrideImmediateScanJobId);
        return sOverrideImmediateScanJobId;
    }
    return getJobIdFromManifest(context, "immediateScanJobId");
}
 
Example 13
Source File: ScanJob.java    From android-beacon-library with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 14
Source File: ScanJob.java    From android-beacon-library with Apache License 2.0 5 votes vote down vote up
private void startPassiveScanIfNeeded() {
    if (mScanState != null) {
        LogManager.d(TAG, "Checking to see if we need to start a passive scan");
        boolean insideAnyRegion = false;
        // Clone the collection before iterating to prevent ConcurrentModificationException per #577
        List<Region> regions = new ArrayList<>(mScanState.getMonitoringStatus().regions());
        for (Region region : regions) {
            RegionMonitoringState state = mScanState.getMonitoringStatus().stateOf(region);
            if (state != null && state.getInside()) {
                insideAnyRegion = true;
            }
        }
        if (insideAnyRegion) {
            // TODO: Set up a scan filter for not detecting a beacon pattern
            LogManager.i(TAG, "We are inside a beacon region.  We will not scan between cycles.");
        }
        else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                if (mScanHelper != null) {
                    mScanHelper.startAndroidOBackgroundScan(mScanState.getBeaconParsers());
                }
            }
            else {
                LogManager.d(TAG, "This is not Android O.  No scanning between cycles when using ScanJob");
            }
        }
    }
}
 
Example 15
Source File: ScanHelper.java    From android-beacon-library with Apache License 2.0 5 votes vote down vote up
@WorkerThread
@Override
protected Void doInBackground(ScanHelper.ScanData... params) {
    ScanHelper.ScanData scanData = params[0];
    Beacon beacon = null;

    for (BeaconParser parser : ScanHelper.this.mBeaconParsers) {
        beacon = parser.fromScanData(scanData.scanRecord, scanData.rssi, scanData.device, scanData.timestampMs);

        if (beacon != null) {
            break;
        }
    }
    if (beacon != null) {
        if (LogManager.isVerboseLoggingEnabled()) {
            LogManager.d(TAG, "Beacon packet detected for: "+beacon+" with rssi "+beacon.getRssi());
        }
        mDetectionTracker.recordDetection();
        if (mCycledScanner != null && !mCycledScanner.getDistinctPacketsDetectedPerScan()) {
            if (!mDistinctPacketDetector.isPacketDistinct(scanData.device.getAddress(),
                    scanData.scanRecord)) {
                LogManager.i(TAG, "Non-distinct packets detected in a single scan.  Restarting scans unecessary.");
                mCycledScanner.setDistinctPacketsDetectedPerScan(true);
            }
        }
        processBeaconFromScan(beacon);
    } else {
        if (mNonBeaconLeScanCallback != null) {
            mNonBeaconLeScanCallback.onNonBeaconLeScan(scanData.device, scanData.rssi, scanData.scanRecord);
        }
    }
    return null;
}
 
Example 16
Source File: BeaconService.java    From android-beacon-library with Apache License 2.0 4 votes vote down vote up
@MainThread
@Override
public void handleMessage(Message msg) {
    BeaconService service = mService.get();
    if (service != null) {
        StartRMData startRMData = StartRMData.fromBundle(msg.getData());
        if (startRMData != null) {
            switch (msg.what) {
                case MSG_START_RANGING:
                    LogManager.i(TAG, "start ranging received");
                    service.startRangingBeaconsInRegion(startRMData.getRegionData(), new org.altbeacon.beacon.service.Callback(startRMData.getCallbackPackageName()));
                    service.setScanPeriods(startRMData.getScanPeriod(), startRMData.getBetweenScanPeriod(), startRMData.getBackgroundFlag());
                    break;
                case MSG_STOP_RANGING:
                    LogManager.i(TAG, "stop ranging received");
                    service.stopRangingBeaconsInRegion(startRMData.getRegionData());
                    service.setScanPeriods(startRMData.getScanPeriod(), startRMData.getBetweenScanPeriod(), startRMData.getBackgroundFlag());
                    break;
                case MSG_START_MONITORING:
                    LogManager.i(TAG, "start monitoring received");
                    service.startMonitoringBeaconsInRegion(startRMData.getRegionData(), new org.altbeacon.beacon.service.Callback(startRMData.getCallbackPackageName()));
                    service.setScanPeriods(startRMData.getScanPeriod(), startRMData.getBetweenScanPeriod(), startRMData.getBackgroundFlag());
                    break;
                case MSG_STOP_MONITORING:
                    LogManager.i(TAG, "stop monitoring received");
                    service.stopMonitoringBeaconsInRegion(startRMData.getRegionData());
                    service.setScanPeriods(startRMData.getScanPeriod(), startRMData.getBetweenScanPeriod(), startRMData.getBackgroundFlag());
                    break;
                case MSG_SET_SCAN_PERIODS:
                    LogManager.i(TAG, "set scan intervals received");
                    service.setScanPeriods(startRMData.getScanPeriod(), startRMData.getBetweenScanPeriod(), startRMData.getBackgroundFlag());
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
        else if (msg.what == MSG_SYNC_SETTINGS) {
            LogManager.i(TAG, "Received settings update from other process");
            SettingsData settingsData = SettingsData.fromBundle(msg.getData());
            if (settingsData != null) {
                settingsData.apply(service);
            }
            else {
                LogManager.w(TAG, "Settings data missing");
            }
        }
        else {
            LogManager.i(TAG, "Received unknown message from other process : "+msg.what);
        }

    }
}
 
Example 17
Source File: BeaconService.java    From android-beacon-library with Apache License 2.0 4 votes vote down vote up
public BeaconService getService() {
    LogManager.i(TAG, "getService of BeaconBinder called");
    // Return this instance of LocalService so clients can call public methods
    return BeaconService.this;
}
 
Example 18
Source File: BeaconService.java    From android-beacon-library with Apache License 2.0 4 votes vote down vote up
/**
 * When binding to the service, we return an interface to our messenger
 * for sending messages to the service.
 */
@Override
public IBinder onBind(Intent intent) {
    LogManager.i(TAG, "binding");
    return mMessenger.getBinder();
}
 
Example 19
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);
        }
    }
}
 
Example 20
Source File: BluetoothMedic.java    From android-beacon-library with Apache License 2.0 4 votes vote down vote up
/**
 * Starts up a beacon transmitter with the intent of seeing if it results in an error condition
 * indicating the bluetooth stack may be in a bad state.
 *
 * If the failure error code matches a pattern known to be associated with a bad bluetooth stack
 * state, then the bluetooth stack is turned off and then back on after a short delay in order
 * to try to recover.
 *
 * @return false if the test indicates a failure indicating a bad state of the bluetooth stack
 */
@SuppressWarnings({"unused","WeakerAccess"})
@RequiresApi(21)
public boolean runTransmitterTest(final Context context) {
    initializeWithContext(context);
    this.mTransmitterTestResult = null;
    long testStartTime = System.currentTimeMillis();
    if (mAdapter != null) {
        final BluetoothLeAdvertiser advertiser = getAdvertiserSafely(mAdapter);
        if(advertiser != null) {
            AdvertiseSettings settings = (new Builder()).setAdvertiseMode(0).build();
            AdvertiseData data = (new android.bluetooth.le.AdvertiseData.Builder())
                    .addManufacturerData(0, new byte[]{0}).build();
            LogManager.i(TAG, "Starting transmitter test");
            advertiser.startAdvertising(settings, data, new AdvertiseCallback() {
                public void onStartSuccess(AdvertiseSettings settingsInEffect) {
                    super.onStartSuccess(settingsInEffect);
                    LogManager.i(BluetoothMedic.TAG, "Transmitter test succeeded");
                    advertiser.stopAdvertising(this);
                    BluetoothMedic.this.mTransmitterTestResult = true;
                }

                public void onStartFailure(int errorCode) {
                    super.onStartFailure(errorCode);
                    Intent intent = new Intent("onStartFailed");
                    intent.putExtra("errorCode", errorCode);
                    LogManager.d(BluetoothMedic.TAG, "Sending onStartFailure broadcast with "
                            + BluetoothMedic.this.mLocalBroadcastManager);
                    if (BluetoothMedic.this.mLocalBroadcastManager != null) {
                        BluetoothMedic.this.mLocalBroadcastManager.sendBroadcast(intent);
                    }
                    if(errorCode == 4) {
                        BluetoothMedic.this.mTransmitterTestResult = false;
                        LogManager.w(BluetoothMedic.TAG,
                                "Transmitter test failed in a way we consider a test failure");
                        BluetoothMedic.this.sendNotification(context, "transmitter failed",
                                "bluetooth not ok");
                    } else {
                        BluetoothMedic.this.mTransmitterTestResult = true;
                        LogManager.i(BluetoothMedic.TAG,
                                "Transmitter test failed, but not in a way we consider a test failure");
                    }

                }
            });
        } else {
            LogManager.d(TAG, "Cannot get advertiser");
        }
        while(this.mTransmitterTestResult == null) {
            LogManager.d(TAG, "Waiting for transmitter test to complete...");

            try {
                Thread.sleep(1000L);
            } catch (InterruptedException e) { /* do nothing */ }

            if(System.currentTimeMillis() - testStartTime > 5000L) {
                LogManager.d(TAG, "Timeout running transmitter test");
                break;
            }
        }
    }

    LogManager.d(TAG, "transmitter test complete");
    return this.mTransmitterTestResult != null && this.mTransmitterTestResult;
}