Java Code Examples for android.bluetooth.le.ScanSettings

The following are top voted examples for showing how to use android.bluetooth.le.ScanSettings. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: AsteroidOSSync   File: L_Util.java   Source Code and License 6 votes vote down vote up
@Deprecated
static ScanSettings.Builder buildSettings(BleManager mgr, int scanMode, Interval scanReportDelay) {
    final ScanSettings.Builder builder = new ScanSettings.Builder();
    builder.setScanMode(scanMode);

    if( mgr.getNativeAdapter().isOffloadedScanBatchingSupported() )
    {
        final long scanReportDelay_millis = false == Interval.isDisabled(scanReportDelay) ? scanReportDelay.millis() : 0;
        builder.setReportDelay(scanReportDelay_millis);
    }
    else
    {
        builder.setReportDelay(0);
    }
    return builder;
}
 
Example 2
Project: u2f-ble-test   File: U2FBLEDevice.java   Source Code and License 6 votes vote down vote up
protected static void scanDevice(BluetoothAdapter bluetoothAdapter, U2FBLEDeviceNotification notification, Logger logger, Context context, String data, ScanType scanType) {
	BluetoothLeScanner bluetoothScanner = bluetoothAdapter.getBluetoothLeScanner();
	ScanFilter.Builder builder = new ScanFilter.Builder();
	switch(scanType) {
		case SCAN_BY_NAME:
			builder.setDeviceName(data);
			break;
	}
	Vector<ScanFilter> filter = new Vector<ScanFilter>();
	filter.add(builder.build());
	ScanSettings.Builder builderScanSettings = new ScanSettings.Builder();
	builderScanSettings.setScanMode(ScanSettings.SCAN_MODE_BALANCED);
	builderScanSettings.setReportDelay(0);
	LocalScanCallback scannerCallback = new LocalScanCallback(bluetoothAdapter, logger, notification, context);
	bluetoothScanner.startScan(filter, builderScanSettings.build(), scannerCallback);		
}
 
Example 3
Project: xDrip   File: BluetoothGlucoseMeter.java   Source Code and License 6 votes vote down vote up
private void beginScan() {
    if (Build.VERSION.SDK_INT >= 21) {
        if (d) Log.d(TAG, "Preparing for scan...");

        // set up v21 scanner
        mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
        settings = new ScanSettings.Builder()
                .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                .build();
        filters = new ArrayList<>();

        filters.add(new ScanFilter.Builder().setServiceUuid(new ParcelUuid(GLUCOSE_SERVICE)).build());
    }
    // all api versions
    scanLeDevice(true);
}
 
Example 4
Project: xDrip-plus   File: BluetoothGlucoseMeter.java   Source Code and License 6 votes vote down vote up
private void beginScan() {
    if (Build.VERSION.SDK_INT >= 21) {
        if (d) Log.d(TAG, "Preparing for scan...");

        // set up v21 scanner
        mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
        settings = new ScanSettings.Builder()
                .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                .build();
        filters = new ArrayList<>();

        filters.add(new ScanFilter.Builder().setServiceUuid(new ParcelUuid(GLUCOSE_SERVICE)).build());
    }
    // all api versions
    scanLeDevice(true);
}
 
Example 5
Project: SensorLib   File: DsSensorManager.java   Source Code and License 6 votes vote down vote up
public static void searchBleDeviceByNames(final SensorFoundCallback callback, String[] deviceNames) {
    //Log.e(TAG, "Searching for BLE device...");

    List<ScanFilter> filterList = new ArrayList<>();
    for (String name : deviceNames) {
        filterList.add(new ScanFilter.Builder().setDeviceName(name).build());
    }

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
        if (sBleScanner == null) {
            sBleScanner = BluetoothAdapter.getDefaultAdapter().getBluetoothLeScanner();
        }
        if (sScanCallback == null) {
            sScanCallback = new DsScanCallback(callback);
        }

        if (sBleScanner != null) {
            sBleScanner.startScan(filterList, new ScanSettings.Builder().build(), sScanCallback);
        }
    }
}
 
Example 6
Project: SensorLib   File: DsSensorManager.java   Source Code and License 6 votes vote down vote up
public static void searchBleDeviceByUUIDs(SensorFoundCallback callback, UUID[] uuids) {
    //Log.e(TAG, "Searching for BLE device...");

    List<ScanFilter> filterList = new ArrayList<>();
    for (UUID uuid : uuids) {
        filterList.add(new ScanFilter.Builder().setServiceUuid(new ParcelUuid(uuid)).build());
    }

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
        if (sBleScanner == null) {
            sBleScanner = BluetoothAdapter.getDefaultAdapter().getBluetoothLeScanner();
        }
        if (sScanCallback == null) {
            sScanCallback = new DsScanCallback(callback);
        }

        if (sBleScanner != null) {
            sBleScanner.startScan(filterList, new ScanSettings.Builder().build(), sScanCallback);
        }
    }
}
 
Example 7
Project: AndroidBleManager   File: BluetoothLeScannerCompat.java   Source Code and License 6 votes vote down vote up
@Override
public void startScan(BluetoothAdapter adapter, List<ScanFilterCompat> filters, ScanSettingsCompat settings, ScanCallbackCompat callbackCompat) {

    List<ScanFilter> scanFilters = null;
    if (filters != null) {
        scanFilters = new ArrayList<>(filters.size());

        for (ScanFilterCompat filter : filters) {
            scanFilters.add(filter.toApi21());
        }
    }
    if (settings == null) {
        throw new IllegalStateException("Scan settings are null");
    }
    ScanSettings scanSettings = settings.toApi21();
    adapter.getBluetoothLeScanner().startScan(scanFilters, scanSettings, registerCallback(callbackCompat));
}
 
Example 8
Project: DeviceConnect-Android   File: NewBleDeviceAdapterImpl.java   Source Code and License 6 votes vote down vote up
@Override
public void startScan(final BleDeviceScanCallback callback) {
    mCallback = callback;

    final List<ScanFilter> filters = new ArrayList<>();

    final ScanSettings settings = new ScanSettings.Builder().build();
    mBleScanner = mBluetoothAdapter.getBluetoothLeScanner();

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        if (mBleScanner != null) {
            mBleScanner.startScan(filters, settings, mScanCallback);
        }
    } else {
        // Unless required permissions were acquired, scan does not start.
        if (BleUtils.isBLEPermission(mContext)) {
            if (mBleScanner != null) {
                mBleScanner.startScan(filters, settings, mScanCallback);
            }
        }
    }
}
 
Example 9
Project: DeviceConnect-Android   File: NewBleDeviceAdapterImpl.java   Source Code and License 6 votes vote down vote up
@Override
public void startScan(final BleDeviceScanCallback callback) {
    mCallback = callback;

    List<ScanFilter> filters = new ArrayList<ScanFilter>();
    if (mServiceUuids != null && mServiceUuids.length > 0) {
        for (UUID uuid : mServiceUuids) {
            ScanFilter filter = new ScanFilter.Builder().setServiceUuid(
                    new ParcelUuid(uuid)).build();
            filters.add(filter);
        }
    }
    ScanSettings settings = new ScanSettings.Builder().build();

    mBleScanner = mBluetoothAdapter.getBluetoothLeScanner();
    if (mBleScanner != null) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            mBleScanner.startScan(filters, settings, mScanCallback);
        } else {
            // Unless required permissions were acquired, scan does not start.
            if (BleUtils.isBLEPermission(mContext)) {
                mBleScanner.startScan(filters, settings, mScanCallback);
            }
        }
    }
}
 
Example 10
Project: BluetoothCompat   File: BluetoothLeScannerCompat.java   Source Code and License 6 votes vote down vote up
@Override
public void startScan(BluetoothAdapter adapter, List<ScanFilterCompat> filters, ScanSettingsCompat settings, ScanCallbackCompat callbackCompat) {

    List<ScanFilter> scanFilters = null;
    if (filters != null) {
        scanFilters = new ArrayList<>(filters.size());

        for (ScanFilterCompat filter : filters) {
            scanFilters.add(filter.toApi21());
        }
    }
    if (settings == null) {
        throw new IllegalStateException("Scan settings are null");
    }
    ScanSettings scanSettings = settings.toApi21();
    adapter.getBluetoothLeScanner().startScan(scanFilters, scanSettings, registerCallback(callbackCompat));
}
 
Example 11
Project: android-buruberi   File: LollipopLePeripheralScannerTests.java   Source Code and License 6 votes vote down vote up
@Test
public void concludesAtLimit() {
    final ShadowBluetoothAdapterExt shadowAdapter = getShadowBluetoothAdapter();
    final ShadowBluetoothLeScanner shadowScanner = BuruberiShadows.shadowOf(shadowAdapter.getBluetoothLeScanner());
    final PeripheralCriteria criteria = new PeripheralCriteria();
    criteria.setLimit(1);
    final LollipopLePeripheralScanner scanner = new LollipopLePeripheralScanner(stack, criteria);

    scanner.call(Subscribers.empty());
    assertThat(shadowScanner.getScanCallbacks(), hasItem(scanner));

    final BluetoothDevice device = Testing.createMockDevice();
    final ScanResult scanResult = new ScanResult(device,
                                                  Testing.EMPTY_SCAN_RECORD,
                                                  Testing.RSSI_DECENT,
                                                  SystemClock.elapsedRealtimeNanos());
    scanner.onScanResult(ScanSettings.CALLBACK_TYPE_ALL_MATCHES, scanResult);

    scanner.onConcludeScan();

    assertThat(shadowScanner.getScanCallbacks(), not(hasItem(scanner)));
}
 
Example 12
Project: nearby-beacons   File: EddystoneScannerService.java   Source Code and License 6 votes vote down vote up
private void startScanning() {
    List<ScanFilter> filters = new ArrayList<>();
    //Filter on just our requested namespaces
    for (String namespace : NAMESPACE_IDS) {
        ScanFilter beaconFilter = new ScanFilter.Builder()
                .setServiceUuid(UID_SERVICE)
                .setServiceData(UID_SERVICE, getNamespaceFilter(namespace),
                        NAMESPACE_FILTER_MASK)
                .build();
        filters.add(beaconFilter);
    }

    //Run in background mode
    ScanSettings settings = new ScanSettings.Builder()
            .setScanMode(ScanSettings.SCAN_MODE_LOW_POWER)
            .build();

    mBluetoothLeScanner.startScan(filters, settings, mScanCallback);
    if (DEBUG_SCAN) Log.d(TAG, "Scanning started…");
}
 
Example 13
Project: SweetBlue   File: L_Util.java   Source Code and License 6 votes vote down vote up
@Deprecated
static ScanSettings.Builder buildSettings(BleManager mgr, int scanMode, Interval scanReportDelay) {
    final ScanSettings.Builder builder = new ScanSettings.Builder();
    builder.setScanMode(scanMode);

    if( mgr.getNativeAdapter().isOffloadedScanBatchingSupported() )
    {
        final long scanReportDelay_millis = false == Interval.isDisabled(scanReportDelay) ? scanReportDelay.millis() : 0;
        builder.setReportDelay(scanReportDelay_millis);
    }
    else
    {
        builder.setReportDelay(0);
    }
    return builder;
}
 
Example 14
Project: AndroidSDK2.0   File: DeviceListActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onResume() {
    super.onResume();
    if (Build.VERSION.SDK_INT >= 21) {
        mLeScanner = mBtAdapter.getBluetoothLeScanner();
        mScanSetting = new ScanSettings.Builder()
                .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                .build();
        mScanFilters = new ArrayList<>();
    }
}
 
Example 15
Project: SensorTag-Accelerometer   File: ScanFragment.java   Source Code and License 5 votes vote down vote up
/**
 * Initiates the scan for BLE devices according to the API level.
 */
private void startScan() {
    if (mRecyclerViewAdapter.getSize() == 0) mListener.onShowProgress();
    if (Build.VERSION.SDK_INT < 21) {
        mBluetoothAdapter.startLeScan(mLeScanCallback);
    } else {
        // request BluetoothLeScanner if it hasn't been initialized yet
        if (mLeScanner == null) mLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
        // start scan in low latency mode
        mLeScanner.startScan(new ArrayList<ScanFilter>(), new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build(), mScanCallback);
    }
}
 
Example 16
Project: com.ruuvi.station   File: RuuviTagScanner.java   Source Code and License 5 votes vote down vote up
public RuuviTagScanner(RuuviTagListener listener, Context context) {
    this.listener = listener;
    final BluetoothManager bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
    bluetoothAdapter = bluetoothManager.getAdapter();
    if (useNewApi()) {
        bleScanner = bluetoothAdapter.getBluetoothLeScanner();
        ScanSettings.Builder scanSettingsBuilder = new ScanSettings.Builder();
        scanSettingsBuilder.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY);
        scanSettings = scanSettingsBuilder.build();
    }
}
 
Example 17
Project: mobly-bundled-snippets   File: MbsEnums.java   Source Code and License 5 votes vote down vote up
private static RpcEnum buildBleScanResultCallbackTypeEnum() {
    RpcEnum.Builder builder = new RpcEnum.Builder();
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        return builder.build();
    }
    builder.add("CALLBACK_TYPE_ALL_MATCHES", ScanSettings.CALLBACK_TYPE_ALL_MATCHES);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        builder.add("CALLBACK_TYPE_FIRST_MATCH", ScanSettings.CALLBACK_TYPE_FIRST_MATCH);
        builder.add("CALLBACK_TYPE_MATCH_LOST", ScanSettings.CALLBACK_TYPE_MATCH_LOST);
    }
    return builder.build();
}
 
Example 18
Project: AndroidMuseumBleManager   File: ScanSettingsCompat.java   Source Code and License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
ScanSettings toApi21() {
    return new ScanSettings.Builder()
            .setReportDelay(getReportDelayMillis())
            .setScanMode(getScanMode())
            .build();
}
 
Example 19
Project: igrow-android   File: DeviceScanActivity.java   Source Code and License 5 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getActionBar().setTitle(com.igrow.android.R.string.title_devices);
    mHandler = new Handler();

    // Use this check to determine whether BLE is supported on the device.  Then you can
    // selectively disable BLE-related features.
    if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
        Toast.makeText(this, com.igrow.android.R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
        finish();
    }

    // Initializes a Bluetooth adapter.  For API level 18 and above, get a reference to
    // BluetoothAdapter through BluetoothManager.
    final BluetoothManager bluetoothManager =
            (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    mBluetoothAdapter = bluetoothManager.getAdapter();

    // Checks if Bluetooth is supported on the device.
    if (mBluetoothAdapter == null) {
        Toast.makeText(this, com.igrow.android.R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
        finish();
        return;
    }

    if (android.os.Build.VERSION.SDK_INT >= 21) {
        ScanSettings.Builder scanSettingsBuilder = new ScanSettings.Builder()
                .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY);

        mScanSettings = scanSettingsBuilder.build();
        mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
    }
}
 
Example 20
Project: igrow-android   File: BluetoothLeScanL21Proxy.java   Source Code and License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void startLeScan() {
    List<ScanFilter> filters = new ArrayList<ScanFilter>();
    ScanFilter filter = new ScanFilter.Builder().build();
    filters.add(filter);

    ScanSettings settings = new ScanSettings.Builder().setScanMode(SCAN_MODE_LOW_LATENCY)
            .build();

    mBluetoothLeScanner.startScan(filters, settings, mLeScanCallback);
}
 
Example 21
Project: microbit   File: PairingActivity.java   Source Code and License 5 votes vote down vote up
/**
 * Allows to start or stop scanning for a low energy device.
 *
 * @param enable True - start scanning, false - stop scanning.
 */
private void scanLeDevice(final boolean enable) {
    logi("scanLeDevice() :: enable = " + enable);
    if(enable) {
        //Start scanning.
        if(!setupBleController()) {
            logi("scanLeDevice() :: FAILED ");
            return;
        }
        if(!scanning) {
            logi("scanLeDevice ::   Searching For " + newDeviceName.toLowerCase());
            // Stops scanning after a pre-defined scan period.
            scanning = true;
            ((TextView) findViewById(R.id.search_microbit_step_3_title))
                    .setText(getString(R.string.searchingTitle));
            handler.postDelayed(scanTimedOut, SCAN_PERIOD);
            if(Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                bluetoothAdapter.startLeScan(getOldScanCallback());
            } else {
                List<ScanFilter> filters = new ArrayList<>();
                // TODO: play with ScanSettings further to ensure the Kit kat devices connectMaybeInit with higher success rate
                ScanSettings settings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_BALANCED).build();
                leScanner.startScan(filters, settings, getNewScanCallback());
            }
        }
    } else {
        //Stop scanning.
        if(scanning) {
            scanning = false;
            handler.removeCallbacks(scanTimedOut);
            if(Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                bluetoothAdapter.stopLeScan(getOldScanCallback());
            } else {
                leScanner.stopScan(getNewScanCallback());
            }
        }
    }
}
 
Example 22
Project: AndroidSensors   File: BLEMeasurementsGatherer.java   Source Code and License 5 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void configureSensorSubscribeAndUnsubscribeBehaviors(FlowableEmitter<SensorRecord> subscriber) {
    List<ScanFilter> scanFilters = initializeScanFilters();
    ScanSettings scanSettings = initializeScanSettings();
    final ScanCallback scanCallback = initializeScanCallbackFor(subscriber);

    startListeningBluetoothMeasurements(scanFilters, scanSettings, scanCallback);
    addUnsuscribeCallbackFor(subscriber, scanCallback);
}
 
Example 23
Project: AndroidSensors   File: BLEMeasurementsGatherer.java   Source Code and License 5 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void startListeningBluetoothMeasurements(List<ScanFilter> scanFilters,
                                                 ScanSettings scanSettings,
                                                 ScanCallback scanCallback){
    BluetoothLeScanner scanner = bluetoothManager.getAdapter().getBluetoothLeScanner();
    scanner.startScan(scanFilters, scanSettings, scanCallback);
}
 
Example 24
Project: noise   File: BluetoothSyncService.java   Source Code and License 5 votes vote down vote up
private ScanSettings buildScanSettings() {
    ScanSettings.Builder builder = new ScanSettings.Builder();
    builder.setScanMode(ScanSettings.SCAN_MODE_LOW_POWER);

    if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
        builder.setMatchMode(ScanSettings.MATCH_MODE_AGGRESSIVE);
        builder.setNumOfMatches(ScanSettings.MATCH_NUM_MAX_ADVERTISEMENT);
        builder.setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES);
    }

    return builder.build();
}
 
Example 25
Project: UDOOBluLib-android   File: UdooBluService.java   Source Code and License 5 votes vote down vote up
public void scanLeDevice(final boolean enable, final BluScanCallBack scanCallback) {
    List<ScanFilter> scanFilters = new ArrayList<>();
    ScanFilter scanFilter = new ScanFilter.Builder().setServiceUuid(new ParcelUuid(UDOOBLE.UUID_SENSORS_SERV)).build();
    scanFilters.add(scanFilter);

    ScanSettings scanSettings = new ScanSettings.Builder()
            .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
            .build();

    UdooBluException udooBluException = checkBluetooth(getApplicationContext());
    if (udooBluException != null) {
        if (scanCallback != null)
            scanCallback.onError(udooBluException);
    } else {
        mLEScanner = mBtAdapter.getBluetoothLeScanner();
        if (enable && mScanning.compareAndSet(false, true)) {
            mLEScanner.startScan(scanFilters, scanSettings, scanCallback);
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mLEScanner.stopScan(scanCallback);
                    mScanning.set(false);
                    if (scanCallback != null)
                        scanCallback.onScanFinished();
                }
            }, SCAN_PERIOD);
        } else {
            mScanning.set(false);
            mLEScanner.stopScan(scanCallback);
            if (scanCallback != null)
                scanCallback.onScanFinished();
        }
    }
}
 
Example 26
Project: mesh-core-on-android   File: JniCallbacks.java   Source Code and License 5 votes vote down vote up
private ScanSettings createScanSettings() {
	ScanSettings.Builder builder = new ScanSettings.Builder();
	ScanSettings settings;

	builder.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY);
	builder.setMatchMode(ScanSettings.MATCH_MODE_AGGRESSIVE);
	builder.setNumOfMatches(ScanSettings.MATCH_NUM_ONE_ADVERTISEMENT);
	settings = builder.build();

	return settings;
}
 
Example 27
Project: plen-Scenography_Android   File: PlenScanService.java   Source Code and License 5 votes vote down vote up
private void startScan(@NonNull StartScanRequest request) {
    if (getState() == State.SCANNING) {
        return;
    }

    ScanSettings settings = new ScanSettings.Builder()
            .setScanMode(ScanSettings.SCAN_MODE_LOW_POWER)
            .build();

    mScanResults.clear();
    try {
        BluetoothUtil.getBluetoothAdapter(getApplication())
                .getBluetoothLeScanner()
                .startScan(PlenGattConstants.PLEN_FILTERS, settings, mScanCallback);
    } catch (ScenographyException e) {
        postErrorEvent(e);
        return;
    }

    Observable<Object> stopEvent = Observable.amb(
            Observable.timer(request.getTimeout(), request.getUnit())
                    .doOnNext(t -> stopScan(new StopScanRequest())),
            mState.asObservable()
                    .skipWhile(state -> state != State.SCANNING)
                    .skipWhile(state -> state != State.STOP));
    mSubscriptions.add(stopEvent.first().subscribe());

    mState.set(State.SCANNING);
}
 
Example 28
Project: RxAndroidBle   File: InternalScanResultCreator.java   Source Code and License 5 votes vote down vote up
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
private static ScanCallbackType toScanCallbackType(int callbackType) {
    switch (callbackType) {
        case ScanSettings.CALLBACK_TYPE_ALL_MATCHES:
            return CALLBACK_TYPE_ALL_MATCHES;
        case ScanSettings.CALLBACK_TYPE_FIRST_MATCH:
            return CALLBACK_TYPE_FIRST_MATCH;
        case ScanSettings.CALLBACK_TYPE_MATCH_LOST:
            return CALLBACK_TYPE_MATCH_LOST;
        default:
            RxBleLog.w("Unknown callback type %d -> check android.bluetooth.le.ScanSettings");
            return CALLBACK_TYPE_UNKNOWN;
    }
}
 
Example 29
Project: AsteroidOSSync   File: M_Util.java   Source Code and License 5 votes vote down vote up
@Deprecated
public static void startNativeScan(BleManager mgr, int scanMode, Interval scanReportDelay, L_Util.ScanCallback listener) {
    final ScanSettings.Builder builder = L_Util.buildSettings(mgr, scanMode, scanReportDelay);

    builder.setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES);
    builder.setMatchMode(ScanSettings.MATCH_MODE_AGGRESSIVE);
    builder.setNumOfMatches(ScanSettings.MATCH_NUM_MAX_ADVERTISEMENT);

    final ScanSettings scanSettings = builder.build();

    L_Util.startScan(mgr, scanSettings, listener);
}
 
Example 30
Project: AsteroidOSSync   File: M_Util.java   Source Code and License 5 votes vote down vote up
public static void startNativeScan(BluetoothAdapter adapter, int scanMode, Interval scanReportDelay, L_Util.ScanCallback listener) {
    final ScanSettings.Builder builder = L_Util.buildSettings(adapter, scanMode, scanReportDelay);

    builder.setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES);
    builder.setMatchMode(ScanSettings.MATCH_MODE_AGGRESSIVE);
    builder.setNumOfMatches(ScanSettings.MATCH_NUM_MAX_ADVERTISEMENT);

    final ScanSettings scanSettings = builder.build();

    L_Util.startScan(adapter, scanSettings, listener);
}
 
Example 31
Project: AsteroidOSSync   File: L_Util.java   Source Code and License 5 votes vote down vote up
static ScanSettings.Builder buildSettings(BluetoothAdapter adapter, int scanMode, Interval scanReportDelay) {
    final ScanSettings.Builder builder = new ScanSettings.Builder();
    builder.setScanMode(scanMode);

    if( adapter.isOffloadedScanBatchingSupported() )
    {
        final long scanReportDelay_millis = false == Interval.isDisabled(scanReportDelay) ? scanReportDelay.millis() : 0;
        builder.setReportDelay(scanReportDelay_millis);
    }
    else
    {
        builder.setReportDelay(0);
    }
    return builder;
}
 
Example 32
Project: science-journal   File: DeviceDiscovererV21.java   Source Code and License 5 votes vote down vote up
@Override
public void onStartScanning() {
    mScanner = getBluetoothAdapter().getBluetoothLeScanner();
    List<ScanFilter> filters = new ArrayList<>();
    for (BleServiceSpec spec : BluetoothSensor.SUPPORTED_SERVICES) {
        filters.add(new ScanFilter.Builder()
                .setServiceUuid(ParcelUuid.fromString(spec.getServiceId().toString()))
                .build());
    }
    ScanSettings settings = new ScanSettings.Builder()
            .setScanMode(ScanSettings.SCAN_MODE_BALANCED)
            .build();
    mScanner.startScan(filters, settings, mCallback);
}
 
Example 33
Project: TappyBLE   File: LollipopUtils.java   Source Code and License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static int convertNativeStatusToCompat(int nativeStatus) {
    switch (nativeStatus) {
        case ScanSettings.CALLBACK_TYPE_FIRST_MATCH:
            return com.taptrack.tcmptappy.blescannercompat.ScanSettings.CALLBACK_TYPE_FIRST_MATCH;
        case ScanSettings.CALLBACK_TYPE_MATCH_LOST:
            return com.taptrack.tcmptappy.blescannercompat.ScanSettings.CALLBACK_TYPE_MATCH_LOST;
        default:
        case ScanSettings.CALLBACK_TYPE_ALL_MATCHES:
            return com.taptrack.tcmptappy.blescannercompat.ScanSettings.CALLBACK_TYPE_ALL_MATCHES;
    }
}
 
Example 34
Project: u2f-ble-test   File: MainActivity.java   Source Code and License 5 votes vote down vote up
private void startScan() {
	BluetoothLeScanner bluetoothScanner = bluetoothAdapter.getBluetoothLeScanner();
	ScanFilter.Builder builder = new ScanFilter.Builder();		
	Vector<ScanFilter> filter = new Vector<ScanFilter>();
	filter.add(builder.build());
	ScanSettings.Builder builderScanSettings = new ScanSettings.Builder();		
	builderScanSettings.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY);
	builderScanSettings.setReportDelay(0);
	bluetoothScanner.startScan(filter, builderScanSettings.build(), leScanCallback);
}
 
Example 35
Project: xDrip   File: G5CollectionService.java   Source Code and License 5 votes vote down vote up
public void setupBluetooth() {

        getTransmitterDetails();
        if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
            //First time using the app or bluetooth was turned off?
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            Timer single_timer = new Timer();
            single_timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    if (mBluetoothAdapter != null) mBluetoothAdapter.enable();
                }
            }, 1000);
            single_timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    setupBluetooth();
                }
            }, 10000);
        } else {
            if (Build.VERSION.SDK_INT >= 21) {
                mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
                settings = new ScanSettings.Builder()
                        .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                        .build();
                filters = new ArrayList<>();
                //Only look for CGM.
                //filters.add(new ScanFilter.Builder().setServiceUuid(new ParcelUuid(BluetoothServices.Advertisement)).build());
                String transmitterIdLastTwo = Extensions.lastTwoCharactersOfString(defaultTransmitter.transmitterId);
                filters.add(new ScanFilter.Builder().setDeviceName("Dexcom" + transmitterIdLastTwo).build());
            }

            // unbond here to avoid clashes when we are mid-connection
            if (alwaysUnbond()) {
                forgetDevice();
            }
            JoH.ratelimit("G5-timeout",0);//re-init to ensure onStartCommand always executes cycleScan
            cycleScan(0);
        }
    }
 
Example 36
Project: xDrip   File: BluetoothScan.java   Source Code and License 5 votes vote down vote up
@TargetApi(21)
private void scanLeDeviceLollipop(final boolean enable) {
    if (enable) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            lollipopScanner = bluetooth_adapter.getBluetoothLeScanner();
        }
        if(lollipopScanner != null) {
            Log.d(TAG, "Starting scanner 21");
            // Stops scanning after a pre-defined scan period.
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    is_scanning = false;
                    if(bluetooth_adapter != null && bluetooth_adapter.isEnabled()) {
                        lollipopScanner.stopScan(mScanCallback);
                    }
                    invalidateOptionsMenu();
                }
            }, SCAN_PERIOD);
            ScanSettings settings = new ScanSettings.Builder()
                    .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                    .build();
            is_scanning = true;
            lollipopScanner.startScan(null, settings, mScanCallback);
        } else {
            try {
                scanLeDevice(true);
            } catch (Exception e) {
                Log.e(TAG, "Failed to scan for ble device", e);
            }
        }
    } else {
        is_scanning = false;
        if(bluetooth_adapter != null && bluetooth_adapter.isEnabled()) {
            lollipopScanner.stopScan(mScanCallback);
        }
    }
    invalidateOptionsMenu();
}
 
Example 37
Project: xDrip-plus   File: G5CollectionService.java   Source Code and License 5 votes vote down vote up
public void setupBluetooth() {

        getTransmitterDetails();
        if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
            //First time using the app or bluetooth was turned off?
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            Timer single_timer = new Timer();
            single_timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    if (mBluetoothAdapter != null) mBluetoothAdapter.enable();
                }
            }, 1000);
            single_timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    setupBluetooth();
                }
            }, 10000);
        } else {
            if (Build.VERSION.SDK_INT >= 21) {
                mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
                settings = new ScanSettings.Builder()
                        .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                        .build();
                filters = new ArrayList<>();
                //Only look for CGM.
                //filters.add(new ScanFilter.Builder().setServiceUuid(new ParcelUuid(BluetoothServices.Advertisement)).build());
                String transmitterIdLastTwo = Extensions.lastTwoCharactersOfString(defaultTransmitter.transmitterId);
                filters.add(new ScanFilter.Builder().setDeviceName("Dexcom" + transmitterIdLastTwo).build());
            }

            // unbond here to avoid clashes when we are mid-connection
            if (alwaysUnbond()) {
                forgetDevice();
            }
            JoH.ratelimit("G5-timeout",0);//re-init to ensure onStartCommand always executes cycleScan
            cycleScan(0);
        }
    }
 
Example 38
Project: xDrip-plus   File: BluetoothScan.java   Source Code and License 5 votes vote down vote up
@TargetApi(21)
private void scanLeDeviceLollipop(final boolean enable) {
    if (enable) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            lollipopScanner = bluetooth_adapter.getBluetoothLeScanner();
        }
        if(lollipopScanner != null) {
            Log.d(TAG, "Starting scanner 21");
            // Stops scanning after a pre-defined scan period.
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    is_scanning = false;
                    if(bluetooth_adapter != null && bluetooth_adapter.isEnabled()) {
                        lollipopScanner.stopScan(mScanCallback);
                    }
                    invalidateOptionsMenu();
                }
            }, SCAN_PERIOD);
            ScanSettings settings = new ScanSettings.Builder()
                    .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                    .build();
            is_scanning = true;
            lollipopScanner.startScan(null, settings, mScanCallback);
        } else {
            try {
                scanLeDevice(true);
            } catch (Exception e) {
                Log.e(TAG, "Failed to scan for ble device", e);
            }
        }
    } else {
        is_scanning = false;
        if(bluetooth_adapter != null && bluetooth_adapter.isEnabled()) {
            lollipopScanner.stopScan(mScanCallback);
        }
    }
    invalidateOptionsMenu();
}
 
Example 39
Project: ibeacon-scanner-android   File: DefaultScanService.java   Source Code and License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static ScanSettings getScanSettings()
{
    final ScanSettings.Builder builder = new ScanSettings.Builder();
    builder.setReportDelay(0);
    builder.setScanMode(ScanSettings.SCAN_MODE_LOW_POWER);
    return builder.build();
}
 
Example 40
Project: Android-BLE-Library   File: BLEScanner.java   Source Code and License 5 votes vote down vote up
private void initScanData() {
    scanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);
            Log.i(TAG, "onScanResult" + result);
            String address = result.getDevice().getAddress();
            String name;
            ScanRecord scanRecord = result.getScanRecord();
            name = scanRecord == null ? "unknown" : scanRecord.getDeviceName();
            scanResultListener.onResultReceived(name, address);
        }

        @Override
        public void onBatchScanResults(List<ScanResult> results) {
            super.onBatchScanResults(results);
            Log.e(TAG, "onBatchScanResults");
        }

        @Override
        public void onScanFailed(int errorCode) {
            super.onScanFailed(errorCode);
            Log.e(TAG, "onScanFailed");
            scanResultListener.onScanFailed(errorCode);
        }
    };
    filters = new ArrayList<>();
    filters.add(new ScanFilter.Builder().setServiceUuid(ParcelUuid.fromString(BLEProfile.UUID_SERVICE)).build());
    scanSettings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();
}
 
Example 41
Project: livingCity-Android   File: BeaconLollipopActivity.java   Source Code and License 5 votes vote down vote up
private void startScan() {
    //Scan for devices advertising the thermometer service
    ScanFilter beaconFilter = new ScanFilter.Builder()
            .setServiceUuid(TemperatureBeacon.THERM_SERVICE)
            .build();
    ArrayList<ScanFilter> filters = new ArrayList<ScanFilter>();
    filters.add(beaconFilter);

    ScanSettings settings = new ScanSettings.Builder()
            .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
            .build();

    mBluetoothLeScanner.startScan(filters, settings, mScanCallback);
}
 
Example 42
Project: probeZero   File: DeviceRanging.java   Source Code and License 5 votes vote down vote up
public void resumeScan() {
    if (mBleAdapter == null || !mBleAdapter.isEnabled()) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        mContext.startActivity(enableBtIntent);
    } else {
        if (Build.VERSION.SDK_INT >= 21) {
            mLEScanner = mBleAdapter.getBluetoothLeScanner();
            mSettings = new ScanSettings.Builder()
                    .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                    .build();
            mFilters = new ArrayList<ScanFilter>();
        }
        scanLeDevice(true);
    }
}
 
Example 43
Project: AndroidBleManager   File: ScanSettingsCompat.java   Source Code and License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
ScanSettings toApi21() {
    return new ScanSettings.Builder()
            .setReportDelay(getReportDelayMillis())
            .setScanMode(getScanMode())
            .build();
}
 
Example 44
Project: UdooWtf   File: MainActivity.java   Source Code and License 5 votes vote down vote up
private void startScanner() {
    BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(MainActivity.BLUETOOTH_SERVICE);
    BluetoothAdapter adapter = bluetoothManager.getAdapter();
    scanner = adapter.getBluetoothLeScanner();
    ScanSettings settings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_BALANCED).build();
    // scanner.startScan(scanFilters(), settings, scanCallback);
    scanner.startScan(scanCallback);
    System.out.println("Scanner started");
}
 
Example 45
Project: UdooWtf   File: Scanner.java   Source Code and License 5 votes vote down vote up
private void startScanner() {
    BluetoothManager bluetoothManager = (BluetoothManager) activity.getSystemService(activity.BLUETOOTH_SERVICE);
    BluetoothAdapter adapter = bluetoothManager.getAdapter();
    scanner = adapter.getBluetoothLeScanner();
    ScanSettings settings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_BALANCED).build();
   // scanner.startScan(scanFilters(), settings, scanCallback);
    scanner.startScan(scanCallback);
    System.out.println("Scanner started");
}
 
Example 46
Project: BluetoothCompat   File: ScanSettingsCompat.java   Source Code and License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
ScanSettings toApi21() {
    return new ScanSettings.Builder()
            .setReportDelay(getReportDelayMillis())
            .setScanMode(getScanMode())
            .build();
}
 
Example 47
Project: android-buruberi   File: LollipopLePeripheralScanner.java   Source Code and License 5 votes vote down vote up
@Override
@RequiresPermission(Manifest.permission.BLUETOOTH_ADMIN)
public void call(Subscriber<? super List<GattPeripheral>> subscriber) {
    logger.info(BluetoothStack.LOG_TAG, "Beginning Scan (Lollipop impl)");

    this.subscriber = subscriber;

    if (scanner != null) {
        this.scanning = true;

        // Guards against the checking the power state of the BluetoothAdapter,
        // then the power state changing between that check and the following
        // call to startScan.
        try {
            final ScanSettings.Builder builder = new ScanSettings.Builder();
            builder.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY);
            scanner.startScan(null, builder.build(), this);
        } catch (IllegalStateException e) {
            this.scanning = false;
            subscriber.onError(new UserDisabledBuruberiException(e));

            return;
        }

        this.timeout = stack.getScheduler()
                            .createWorker()
                            .schedule(new Action0() {
                                @Override
                                public void call() {
                                    onConcludeScan();
                                }
                            }, peripheralCriteria.duration, TimeUnit.MILLISECONDS);
    } else {
        subscriber.onError(new UserDisabledBuruberiException());
    }
}
 
Example 48
Project: android-buruberi   File: LollipopLePeripheralScanner.java   Source Code and License 5 votes vote down vote up
@Override
@RequiresPermission(allOf = {
        Manifest.permission.BLUETOOTH,
        Manifest.permission.BLUETOOTH_ADMIN,
})
public void onBatchScanResults(List<ScanResult> results) {
    logger.info(BluetoothStack.LOG_TAG, "Forwarding batch results");

    for (ScanResult result : results) {
        onScanResult(ScanSettings.CALLBACK_TYPE_ALL_MATCHES, result);
    }
}
 
Example 49
Project: android-buruberi   File: LollipopLePeripheralScannerTests.java   Source Code and License 5 votes vote down vote up
@Test
public void coalescesResults() {
    final ShadowBluetoothAdapterExt shadowAdapter = getShadowBluetoothAdapter();
    final ShadowBluetoothLeScanner shadowScanner = BuruberiShadows.shadowOf(shadowAdapter.getBluetoothLeScanner());
    final PeripheralCriteria criteria = new PeripheralCriteria();
    final LollipopLePeripheralScanner scanner = new LollipopLePeripheralScanner(stack, criteria);

    scanner.call(Subscribers.empty());
    assertThat(shadowScanner.getScanCallbacks(), hasItem(scanner));

    final BluetoothDevice device = Testing.createMockDevice();
    final ScanResult scanResult1 = new ScanResult(device,
                                                 Testing.EMPTY_SCAN_RECORD,
                                                 Testing.RSSI_DECENT,
                                                 SystemClock.elapsedRealtimeNanos());
    scanner.onScanResult(ScanSettings.CALLBACK_TYPE_ALL_MATCHES, scanResult1);

    final ScannedPeripheral scannedPeripheral = scanner.results.get(device.getAddress());
    assertThat(scannedPeripheral, is(notNullValue()));
    assertThat(scannedPeripheral.rssi, is(equalTo(Testing.RSSI_DECENT)));

    final ScanResult scanResult2 = new ScanResult(device,
                                                 Testing.EMPTY_SCAN_RECORD,
                                                 Testing.RSSI_BETTER,
                                                 SystemClock.elapsedRealtimeNanos());
    scanner.onScanResult(ScanSettings.CALLBACK_TYPE_ALL_MATCHES, scanResult2);

    final ScannedPeripheral scannedPeripheralAgain = scanner.results.get(device.getAddress());
    assertThat(scannedPeripheralAgain, is(notNullValue()));
    assertThat(scannedPeripheralAgain.rssi, is(equalTo(Testing.RSSI_BETTER)));
    assertThat(scannedPeripheralAgain, is(sameInstance(scannedPeripheral)));

    scanner.onConcludeScan();

    assertThat(shadowScanner.getScanCallbacks(), not(hasItem(scanner)));
}
 
Example 50
Project: android-buruberi   File: LollipopLePeripheralScannerTests.java   Source Code and License 5 votes vote down vote up
@Test
public void filtersByAdvertisingData() {
    final String serviceIdentifier = "23D1BCEA5F782315DEEF1212E1FE0000";
    final ShadowBluetoothAdapterExt shadowAdapter = getShadowBluetoothAdapter();
    final ShadowBluetoothLeScanner shadowScanner = BuruberiShadows.shadowOf(shadowAdapter.getBluetoothLeScanner());
    final PeripheralCriteria criteria = new PeripheralCriteria();
    criteria.addExactMatchPredicate(AdvertisingData.TYPE_SERVICE_DATA_128_BIT_UUID,
                                    serviceIdentifier);
    final LollipopLePeripheralScanner scanner = new LollipopLePeripheralScanner(stack, criteria);

    scanner.call(Subscribers.empty());
    assertThat(shadowScanner.getScanCallbacks(), hasItem(scanner));

    final BluetoothDevice device1 = Testing.createMockDevice();
    final byte[] advertisingData1 = new AdvertisingDataBuilder()
            .add(AdvertisingData.TYPE_SERVICE_DATA_128_BIT_UUID, serviceIdentifier)
            .buildRaw();
    final ScanResult scanResult1 = new ScanResult(device1,
                                                  Testing.parseScanRecordFromBytes(advertisingData1),
                                                  Testing.RSSI_DECENT,
                                                  SystemClock.elapsedRealtimeNanos());
    scanner.onScanResult(ScanSettings.CALLBACK_TYPE_ALL_MATCHES, scanResult1);

    final BluetoothDevice device2 = Testing.createMockDevice("BA:BE:CA:FE:BE:EF");
    final byte[] advertisingData2 = new AdvertisingDataBuilder()
            .add(AdvertisingData.TYPE_SERVICE_DATA_128_BIT_UUID,
                 "00D1BCEA5F782315DEEF1212E1FE00FF")
            .buildRaw();
    final ScanResult scanResult2 = new ScanResult(device2,
                                                  Testing.parseScanRecordFromBytes(advertisingData2),
                                                  Testing.RSSI_DECENT,
                                                  SystemClock.elapsedRealtimeNanos());
    scanner.onScanResult(ScanSettings.CALLBACK_TYPE_ALL_MATCHES, scanResult2);

    scanner.onConcludeScan();

    assertThat(shadowScanner.getScanCallbacks(), not(hasItem(scanner)));
    assertThat(scanner.results.keySet(), hasItem(Testing.DEVICE_ADDRESS));
    assertThat(scanner.results.keySet(), not(hasItem("BA:BE:CA:FE:BE:EF")));
}
 
Example 51
Project: android-buruberi   File: LollipopLePeripheralScannerTests.java   Source Code and License 5 votes vote down vote up
@Test
public void filtersByAddress() {
    final ShadowBluetoothAdapterExt shadowAdapter = getShadowBluetoothAdapter();
    final ShadowBluetoothLeScanner shadowScanner = BuruberiShadows.shadowOf(shadowAdapter.getBluetoothLeScanner());
    final PeripheralCriteria criteria = new PeripheralCriteria();
    criteria.addPeripheralAddress(Testing.DEVICE_ADDRESS);
    final LollipopLePeripheralScanner scanner = new LollipopLePeripheralScanner(stack, criteria);

    scanner.call(Subscribers.empty());
    assertThat(shadowScanner.getScanCallbacks(), hasItem(scanner));

    final BluetoothDevice device1 = Testing.createMockDevice();
    final ScanResult scanResult1 = new ScanResult(device1,
                                                 Testing.EMPTY_SCAN_RECORD,
                                                 Testing.RSSI_DECENT,
                                                 SystemClock.elapsedRealtimeNanos());
    scanner.onScanResult(ScanSettings.CALLBACK_TYPE_ALL_MATCHES, scanResult1);

    final BluetoothDevice device2 = Testing.createMockDevice("BA:BE:CA:FE:BE:EF");
    final ScanResult scanResult2 = new ScanResult(device2,
                                                  Testing.EMPTY_SCAN_RECORD,
                                                  Testing.RSSI_DECENT,
                                                  SystemClock.elapsedRealtimeNanos());
    scanner.onScanResult(ScanSettings.CALLBACK_TYPE_ALL_MATCHES, scanResult2);

    scanner.onConcludeScan();

    assertThat(shadowScanner.getScanCallbacks(), not(hasItem(scanner)));
    assertThat(scanner.results.keySet(), hasItem(Testing.DEVICE_ADDRESS));
    assertThat(scanner.results.keySet(), not(hasItem("BA:BE:CA:FE:BE:EF")));
}
 
Example 52
Project: android-buruberi   File: LollipopLePeripheralScannerTests.java   Source Code and License 5 votes vote down vote up
@Test
public void suppressesResultsWhenAdapterOff() {
    final ShadowBluetoothAdapterExt shadowAdapter = getShadowBluetoothAdapter();
    final ShadowBluetoothLeScanner shadowScanner = BuruberiShadows.shadowOf(shadowAdapter.getBluetoothLeScanner());
    final PeripheralCriteria criteria = new PeripheralCriteria();
    final LollipopLePeripheralScanner scanner = new LollipopLePeripheralScanner(stack, criteria);

    scanner.call(new Subscriber<List<GattPeripheral>>() {
        @Override
        public void onCompleted() {
        }

        @Override
        public void onError(Throwable e) {
            fail(e.getMessage());
        }

        @Override
        public void onNext(List<GattPeripheral> gattPeripherals) {
            assertThat(gattPeripherals, is(empty()));
        }
    });
    assertThat(shadowScanner.getScanCallbacks(), hasItem(scanner));

    final BluetoothDevice device = Testing.createMockDevice();
    final ScanResult scanResult = new ScanResult(device,
                                                 Testing.EMPTY_SCAN_RECORD,
                                                 Testing.RSSI_DECENT,
                                                 SystemClock.elapsedRealtimeNanos());
    scanner.onScanResult(ScanSettings.CALLBACK_TYPE_ALL_MATCHES, scanResult);

    assertThat(scanner.results.keySet(), is(not(empty())));

    shadowAdapter.setState(BluetoothAdapter.STATE_OFF);
    scanner.onConcludeScan();
}
 
Example 53
Project: android-buruberi   File: ShadowBluetoothLeScanner.java   Source Code and License 5 votes vote down vote up
@Implementation
@RequiresPermission(Manifest.permission.BLUETOOTH)
public void startScan(List<ScanFilter> filters,
                      ScanSettings settings,
                      ScanCallback callback) {
    if (adapter.getState() != BluetoothAdapter.STATE_ON) {
        throw new IllegalStateException("BT Adapter is not turned ON");
    }

    scanCallbacks.add(callback);
}
 
Example 54
Project: xDrip-Experimental   File: BluetoothScan.java   Source Code and License 5 votes vote down vote up
@TargetApi(21)
private void scanLeDeviceLollipop(final boolean enable) {
    if (enable) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            lollipopScanner = bluetooth_adapter.getBluetoothLeScanner();
        }
        if(lollipopScanner != null) {
            Log.d(TAG, "Starting scanner 21");
            // Stops scanning after a pre-defined scan period.
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    is_scanning = false;
                    if(bluetooth_adapter != null && bluetooth_adapter.isEnabled()) {
                        lollipopScanner.stopScan(mScanCallback);
                    }
                    invalidateOptionsMenu();
                }
            }, SCAN_PERIOD);
            ScanSettings settings = new ScanSettings.Builder()
                    .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                    .build();
            is_scanning = true;
            lollipopScanner.startScan(null, settings, mScanCallback);
        } else {
            try {
                scanLeDevice(true);
            } catch (Exception e) {
                Log.e(TAG, "Failed to scan for ble device", e);
            }
        }
    } else {
        is_scanning = false;
        if(bluetooth_adapter != null && bluetooth_adapter.isEnabled()) {
            lollipopScanner.stopScan(mScanCallback);
        }
    }
    invalidateOptionsMenu();
}
 
Example 55
Project: xDrip-Experimental   File: G5CollectionService.java   Source Code and License 5 votes vote down vote up
public void setupBluetooth() {
    getTransmitterDetails();
    if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
        //First time using the app or bluetooth was turned off?
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        Timer single_timer = new Timer();
            single_timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    mBluetoothAdapter.enable();
                }
            }, 1000);
        single_timer.schedule(new TimerTask() {
            @Override
            public void run() {
                setupBluetooth();
            }
        }, 10000);
    } else {
        if (Build.VERSION.SDK_INT >= 21) {
            mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
            settings = new ScanSettings.Builder()
                    .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                    .build();
            filters = new ArrayList<>();
            //Only look for CGM.
            //filters.add(new ScanFilter.Builder().setServiceUuid(new ParcelUuid(BluetoothServices.Advertisement)).build());
            String transmitterIdLastTwo = Extensions.lastTwoCharactersOfString(defaultTransmitter.transmitterId);
            filters.add(new ScanFilter.Builder().setDeviceName("Dexcom" + transmitterIdLastTwo).build());
        }

        cycleScan(0);
    }
}
 
Example 56
Project: SuperPanel   File: Ble.java   Source Code and License 5 votes vote down vote up
public Ble(Context c, BleListener i, String deviceUuid, String r, String t)
{
    context = c;
    iface = i;
    superPanelUuid = ParcelUuid.fromString(deviceUuid);
    rxUUid = UUID.fromString(r);
    txUUid = UUID.fromString(t);

    adapter = BluetoothAdapter.getDefaultAdapter();
    scanner = adapter.getBluetoothLeScanner();

    ScanFilter.Builder filter = new ScanFilter.Builder();
    filter.setServiceUuid(superPanelUuid);

    ScanFilter.Builder superPanelFilter = new ScanFilter.Builder();
    superPanelFilter.setServiceUuid(superPanelUuid);

    ScanSettings.Builder settings = new ScanSettings.Builder();
    settings.setScanMode(ScanSettings.SCAN_MODE_LOW_POWER);

    List<ScanFilter> filters = new ArrayList<ScanFilter>();
    filters.add(filter.build());
    //filters.add(superPanelFilter.build());

    if(scanner == null)
    {
        System.out.println("Failed to get LE scanner");
        return;
    }
    scanner.startScan(filters, settings.build(), scanCallback);
}
 
Example 57
Project: 365browser   File: Wrappers.java   Source Code and License 5 votes vote down vote up
public void startScan(
        List<ScanFilter> filters, int scanSettingsScanMode, ScanCallbackWrapper callback) {
    ScanSettings settings =
            new ScanSettings.Builder().setScanMode(scanSettingsScanMode).build();

    ForwardScanCallbackToWrapper callbackForwarder =
            new ForwardScanCallbackToWrapper(callback);
    mCallbacks.put(callback, callbackForwarder);

    mScanner.startScan(filters, settings, callbackForwarder);
}
 
Example 58
Project: BTLEDataLogger   File: DeviceScanActivity.java   Source Code and License 5 votes vote down vote up
public void scanBTLEDevices(final boolean enable) {
    if(bluetoothAdapter == null || bluetoothAdapter.getBluetoothLeScanner() == null) {
        Log.d("BTLE", "Bluetooth adapter or scanner were null!");
        return;
    }

    if(enable) {
        // only scan for 5 seconds
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                scanBTLEDevices(false);
            }
        }, 5000);

        //scanning = true;
        setScanning(true);

        bluetoothDevices.clear();
        deviceRSSIs.clear();
        adapter.notifyDataSetChanged();

        // filter explicitly for the UART
        List<ScanFilter> filters = new ArrayList<ScanFilter>();
        filters.add(new ScanFilter.Builder().setServiceUuid(ParcelUuid.fromString("6E400001-B5A3-F393-E0A9-E50E24DCCA9E")).build());

        // setup the scan settings
        ScanSettings settings = new ScanSettings.Builder().setReportDelay(0).setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();

        bluetoothAdapter.getBluetoothLeScanner().startScan(filters, settings, scanCallback);
    }
    else {
        //scanning = false;
        setScanning(false);
        bluetoothAdapter.getBluetoothLeScanner().stopScan(scanCallback);
    }
}
 
Example 59
Project: proximity-manager   File: BeaconRegisterActivity.java   Source Code and License 5 votes vote down vote up
private void startScan() {
    //Return only Eddystone beacons matching the filter
    ScanFilter beaconFilter = new ScanFilter.Builder()
            .setServiceUuid(UID_SERVICE)
            .setServiceData(UID_SERVICE, Beacon.FRAME_FILTER, Beacon.FILTER_MASK)
            .build();
    List<ScanFilter> filters = Collections.singletonList(beaconFilter);

    ScanSettings settings = new ScanSettings.Builder()
            .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
            .build();

    mBluetoothLeScanner.startScan(filters, settings, mScanCallback);
}
 
Example 60
Project: SweetBlue   File: M_Util.java   Source Code and License 5 votes vote down vote up
@Deprecated
public static void startNativeScan(BleManager mgr, int scanMode, Interval scanReportDelay, L_Util.ScanCallback listener) {
    final ScanSettings.Builder builder = L_Util.buildSettings(mgr, scanMode, scanReportDelay);

    builder.setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES);
    builder.setMatchMode(ScanSettings.MATCH_MODE_AGGRESSIVE);
    builder.setNumOfMatches(ScanSettings.MATCH_NUM_MAX_ADVERTISEMENT);

    final ScanSettings scanSettings = builder.build();

    L_Util.startScan(mgr, scanSettings, listener);
}