android.bluetooth.le.ScanSettings Java Examples

The following examples show how to use android.bluetooth.le.ScanSettings. 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: bitgatt   Author: Fitbit   File: PeripheralScannerTest.java    License: Mozilla Public License 2.0 8 votes vote down vote up
@Test
public void testConnectionAlreadyInMapDisconnectedScanResult() {
    MockScanResultProvider provider = new MockScanResultProvider(10, -167, -40);
    peripheralScanner.addRssiFilter(-10);
    ScanResult result = provider.getAllResults().get(0);
    FitbitBluetoothDevice device = new FitbitBluetoothDevice(result.getDevice());
    GattConnection conn = new GattConnection(device, mockLooper);
    conn.setMockMode(true);
    conn.setState(GattState.DISCONNECTED);
    gatt.getConnectionMap().put(device, conn);
    NoOpGattCallback cb = new NoOpGattCallback() {

        @Override
        public void onBluetoothPeripheralDiscovered(@NonNull GattConnection connection) {
            Assert.assertEquals(conn, connection);
            gatt.unregisterGattEventListener(this);
        }

    };
    gatt.registerGattEventListener(cb);
    peripheralScanner.populateMockScanResultIndividualValue(ScanSettings.CALLBACK_TYPE_FIRST_MATCH, result);
}
 
Example #2
Source Project: RxCentralBle   Author: uber   File: LollipopScanner.java    License: Apache License 2.0 7 votes vote down vote up
private void startScan(PublishSubject scanDataSubject) {
  BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
  if (adapter != null && adapter.isEnabled()) {
    // Setting service uuid scan filter failing on Galaxy S6 on Android 7.
    // Other devices and versions of Android have additional issues with Scan Filters.
    // Manually filter on scan operation.  Add a dummy filter to avoid Android 8.1+ enforcement
    // of filters during background scanning.
    List<ScanFilter> filters = new ArrayList<>();
    ScanFilter.Builder scanFilterBuilder = new ScanFilter.Builder();
    filters.add(scanFilterBuilder.build());

    ScanSettings.Builder settingsBuilder = new ScanSettings.Builder();
    settingsBuilder.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY);

    BluetoothLeScanner bleScanner = adapter.getBluetoothLeScanner();
    if (bleScanner != null) {
      bleScanner.startScan(filters, settingsBuilder.build(), scanCallback);
    } else {
      if (RxCentralLogger.isError()) {
        RxCentralLogger.error("startScan - BluetoothLeScanner is null!");
      }

      scanDataSubject.onError(new ConnectionError(SCAN_FAILED));
    }
  } else {
    if (RxCentralLogger.isError()) {
      if (adapter == null) {
        RxCentralLogger.error("startScan - Default Bluetooth Adapter is null!");
      } else {
        RxCentralLogger.error("startScan - Bluetooth Adapter is disabled.");
      }
    }

    scanDataSubject.onError(new ConnectionError(SCAN_FAILED));
  }

}
 
Example #3
Source Project: AndroidDemoProjects   Author: PaulTR   File: MainActivity.java    License: Apache License 2.0 6 votes vote down vote up
private void discover() {
    List<ScanFilter> filters = new ArrayList<ScanFilter>();

    ScanFilter filter = new ScanFilter.Builder()
            .setServiceUuid( new ParcelUuid(UUID.fromString( getString(R.string.ble_uuid ) ) ) )
            .build();
    filters.add( filter );

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

    mBluetoothLeScanner.startScan(filters, settings, mScanCallback);

    mHandler.postDelayed(new Runnable() {
        @Override
        public void run() {
            mBluetoothLeScanner.stopScan(mScanCallback);
        }
    }, 10000);
}
 
Example #4
Source Project: blessed-android   Author: weliem   File: BluetoothCentral.java    License: MIT License 6 votes vote down vote up
/**
 * Set the default scanMode.
 *
 * <p>Must be ScanSettings.SCAN_MODE_LOW_POWER, ScanSettings.SCAN_MODE_LOW_LATENCY, ScanSettings.SCAN_MODE_BALANCED or ScanSettings.SCAN_MODE_OPPORTUNISTIC.
 * The default value is SCAN_MODE_LOW_LATENCY.
 *
 * @param scanMode the scanMode to set
 * @return true if a valid scanMode was provided, otherwise false
 */
public boolean setScanMode(int scanMode) {
    if (scanMode == ScanSettings.SCAN_MODE_LOW_POWER ||
            scanMode == ScanSettings.SCAN_MODE_LOW_LATENCY ||
            scanMode == ScanSettings.SCAN_MODE_BALANCED ||
            scanMode == ScanSettings.SCAN_MODE_OPPORTUNISTIC) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            this.scanSettings = new ScanSettings.Builder()
                    .setScanMode(scanMode)
                    .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
                    .setMatchMode(ScanSettings.MATCH_MODE_AGGRESSIVE)
                    .setNumOfMatches(ScanSettings.MATCH_NUM_ONE_ADVERTISEMENT)
                    .setReportDelay(0L)
                    .build();
        } else {
            this.scanSettings = new ScanSettings.Builder()
                    .setScanMode(scanMode)
                    .setReportDelay(0L)
                    .build();
        }
        return true;
    }
    return false;
}
 
Example #5
Source Project: blessed-android   Author: weliem   File: BluetoothCentralTest.java    License: MIT License 6 votes vote down vote up
@Test
public void stopScanTest() throws Exception {
    application.grantPermissions(Manifest.permission.ACCESS_COARSE_LOCATION);
    central.scanForPeripherals();
    verify(scanner).startScan(anyList(), any(ScanSettings.class), any(ScanCallback.class));

    // Grab the scan callback that is used
    Field field = BluetoothCentral.class.getDeclaredField("scanByServiceUUIDCallback");
    field.setAccessible(true);
    ScanCallback scanCallback = (ScanCallback) field.get(central);

    // Stop scan
    central.stopScan();

    // Check if scan is correctly stopped
    verify(scanner).stopScan(scanCallback);

    // Stop scan again
    central.stopScan();

    // Verify that stopScan is not called again
    verify(scanner, times(1)).stopScan(any(ScanCallback.class));
}
 
Example #6
Source Project: blessed-android   Author: weliem   File: BluetoothCentralTest.java    License: MIT License 6 votes vote down vote up
@Test
public void autoconnectTwice() throws Exception {
    application.grantPermissions(Manifest.permission.ACCESS_COARSE_LOCATION);

    BluetoothPeripheral peripheral = mock(BluetoothPeripheral.class);
    when(peripheral.getAddress()).thenReturn("12:23:34:98:76:54");
    when(peripheral.getType()).thenReturn(BluetoothDevice.DEVICE_TYPE_UNKNOWN);
    central.autoConnectPeripheral(peripheral, peripheralCallback);

    verify(peripheral, never()).autoConnect();
    verify(scanner).startScan(anyList(), any(ScanSettings.class), any(ScanCallback.class));

    central.autoConnectPeripheral(peripheral, peripheralCallback);

    verify(peripheral, never()).autoConnect();
}
 
Example #7
Source Project: bitgatt   Author: Fitbit   File: MockLollipopScanner.java    License: Mozilla Public License 2.0 6 votes vote down vote up
public BleScanCallbackWrapper(IBluetoothGatt bluetoothGatt,
                              List<ScanFilter> filters, ScanSettings settings,
                              WorkSource workSource, ScanCallback scanCallback,
                              List<List<ResultStorageDescriptor>> resultStorages) {
    mBluetoothGatt = bluetoothGatt;
    mFilters = filters;
    mSettings = settings;
    mWorkSource = workSource;
    mScanCallback = scanCallback;
    mScannerId = 0;
    mResultStorages = resultStorages;
}
 
Example #8
Source Project: bitgatt   Author: Fitbit   File: MockLollipopScanner.java    License: Mozilla Public License 2.0 6 votes vote down vote up
private boolean isSettingsAndFilterComboAllowed(ScanSettings settings,
                                                List<ScanFilter> filterList) {
    final int callbackType = settings.getCallbackType();
    // If onlost/onfound is requested, a non-empty filter is expected
    if ((callbackType & (ScanSettings.CALLBACK_TYPE_FIRST_MATCH
        | ScanSettings.CALLBACK_TYPE_MATCH_LOST)) != 0) {
        if (filterList == null) {
            return false;
        }
        for (ScanFilter filter : filterList) {
            if (filter.equals(EMPTY)) {
                return false;
            }
        }
    }
    return true;
}
 
Example #9
Source Project: easyble-x   Author: wandersnail   File: MyApplication.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    instance = this;
    AppHolder.initialize(this);
    //构建自定义实例,需要在EasyBLE.getInstance()之前
    ScanConfiguration scanConfig = new ScanConfiguration()
            .setScanSettings(new ScanSettings.Builder()
                    .setScanMode(ScanSettings.SCAN_MODE_BALANCED)
                    .build())
            .setScanPeriodMillis(15000)
            .setAcceptSysConnectedDevice(true)
            .setOnlyAcceptBleDevice(true);
    EasyBLE ble = EasyBLE.getBuilder().setScanConfiguration(scanConfig)
            .setObserveAnnotationRequired(false)//不强制使用{@link Observe}注解才会收到被观察者的消息,强制使用的话,性能会好一些
            .setMethodDefaultThreadMode(ThreadMode.BACKGROUND)//指定回调方法和观察者方法的默认线程
            .setScannerType(ScannerType.CLASSIC)
            .build();
    ble.setLogEnabled(true);//开启日志打印
    ble.initialize(this);
}
 
Example #10
Source Project: amazon-freertos-ble-android-sdk   Author: aws   File: AmazonFreeRTOSManager.java    License: Apache License 2.0 6 votes vote down vote up
private void scanLeDevice(long duration) {
    if (mScanning) {
        Log.d(TAG, "Scanning is already in progress.");
        return;
    }
    // Stops scanning after a pre-defined scan period.
    if (duration != 0) {
        mScanHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                stopScanDevices();
            }
        }, duration);
    }
    Log.i(TAG, "Starting ble device scan");
    mScanning = true;

    ScanSettings scanSettings = new ScanSettings.Builder().build();
    mBluetoothLeScanner.startScan(mScanFilters, scanSettings, mScanCallback);
}
 
Example #11
Source Project: SweetBlue   Author: iDevicesInc   File: L_Util.java    License: GNU General Public License v3.0 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 #12
Source Project: com.ruuvi.station   Author: ruuvi   File: ScannerService.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();

    Foreground.init(getApplication());
    Foreground.get().addListener(listener);

    foreground = true;
    scanSettings = new ScanSettings.Builder()
            .setReportDelay(0)
            .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
            .build();
    final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    bluetoothAdapter = bluetoothManager.getAdapter();
    scanner = bluetoothAdapter.getBluetoothLeScanner();

    if (getForegroundMode()) startFG();
    handler = new Handler();
    handler.post(reStarter);
    bgScanHandler = new Handler();
}
 
Example #13
Source Project: bluetooth   Author: JimSeker   File: MainActivity.java    License: Apache License 2.0 6 votes vote down vote up
void discover() {
    mBluetoothLeScanner = BluetoothAdapter.getDefaultAdapter().getBluetoothLeScanner();

    ScanFilter filter = new ScanFilter.Builder()
        .setServiceUuid( new ParcelUuid(UUID.fromString( getString(R.string.ble_uuid ) ) ) )
        .build();
    List<ScanFilter> filters = new ArrayList<ScanFilter>();
    filters.add( filter );

    ScanSettings settings = new ScanSettings.Builder()
        .setScanMode( ScanSettings.SCAN_MODE_LOW_LATENCY )
        .build();
    mBluetoothLeScanner.startScan(filters, settings, mScanCallback);
    mHandler.postDelayed(new Runnable() {
        @Override
        public void run() {
            mBluetoothLeScanner.stopScan(mScanCallback);
        }
    }, 10000);
}
 
Example #14
Source Project: AsteroidOSSync   Author: AsteroidOS   File: L_Util.java    License: GNU General Public License v3.0 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 #15
Source Project: nearby-beacons   Author: devunwired   File: EddystoneScannerService.java    License: MIT 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 #16
Source Project: xDrip   Author: NightscoutFoundation   File: BluetoothGlucoseMeter.java    License: GNU General Public License v3.0 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 #17
Source Project: xDrip-plus   Author: jamorham   File: BluetoothGlucoseMeter.java    License: GNU General Public License v3.0 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 #18
Source Project: AndroidBleManager   Author: haodynasty   File: BluetoothLeScannerCompat.java    License: Apache License 2.0 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 #19
Source Project: blessed-android   Author: weliem   File: BluetoothCentral.java    License: MIT License 5 votes vote down vote up
/**
 * Construct a new BluetoothCentral object
 *
 * @param context                  Android application environment.
 * @param bluetoothCentralCallback the callback to call for updates
 * @param handler                  Handler to use for callbacks.
 */
public BluetoothCentral(Context context, BluetoothCentralCallback bluetoothCentralCallback, Handler handler) {
    if (context == null) {
        Timber.e("context is 'null', cannot create BluetoothCentral");
    }
    if (bluetoothCentralCallback == null) {
        Timber.e("callback is 'null', cannot create BluetoothCentral");
    }
    this.context = context;
    this.bluetoothCentralCallback = bluetoothCentralCallback;
    this.callBackHandler = (handler != null) ? handler : new Handler();
    this.bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        this.autoConnectScanSettings = new ScanSettings.Builder()
                .setScanMode(ScanSettings.SCAN_MODE_LOW_POWER)
                .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
                .setMatchMode(ScanSettings.MATCH_MODE_AGGRESSIVE)
                .setNumOfMatches(ScanSettings.MATCH_NUM_ONE_ADVERTISEMENT)
                .setReportDelay(0L)
                .build();
    } else {
        this.autoConnectScanSettings = new ScanSettings.Builder()
                .setScanMode(ScanSettings.SCAN_MODE_LOW_POWER)
                .setReportDelay(0L)
                .build();
    }
    setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY);

    // Register for broadcasts on BluetoothAdapter state change
    IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    if (context != null) {
        context.registerReceiver(adapterStateReceiver, filter);
    }
}
 
Example #20
Source Project: bluetooth   Author: JimSeker   File: ListenerFragment.java    License: Apache License 2.0 5 votes vote down vote up
public void startScanning() {

        scanner = adapter.getBluetoothLeScanner();
        ScanSettings scanSettings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();
        List<ScanFilter> scanFilters = Arrays.asList(
            new ScanFilter.Builder()
                //.setServiceUuid(ParcelUuid.fromString("some uuid"))
                .build());
        myScanCallback = new MyScanCallback();
        scanner.startScan(scanFilters, scanSettings, myScanCallback);
    }
 
Example #21
Source Project: blessed-android   Author: weliem   File: BluetoothCentralTest.java    License: MIT License 5 votes vote down vote up
@Test
public void scanForPeripheralsWithNamesTest() throws Exception {
    application.grantPermissions(Manifest.permission.ACCESS_COARSE_LOCATION);
    String myName = "Polar";
    central.scanForPeripheralsWithNames(new String[]{myName});

    // Make sure startScan is called
    ArgumentCaptor<List> scanFiltersCaptor = ArgumentCaptor.forClass(List.class);
    ArgumentCaptor<ScanSettings> scanSettingsCaptor = ArgumentCaptor.forClass(ScanSettings.class);
    ArgumentCaptor<ScanCallback> scanCallbackCaptor = ArgumentCaptor.forClass(ScanCallback.class);
    verify(scanner).startScan(scanFiltersCaptor.capture(), scanSettingsCaptor.capture(), scanCallbackCaptor.capture());

    // Verify there is no filter set
    List<ScanFilter> filters = scanFiltersCaptor.getValue();
    assertNull(filters);

    // Grab the scan callback that is used
    Field field = BluetoothCentral.class.getDeclaredField("scanByNameCallback");
    field.setAccessible(true);
    ScanCallback scanCallback = (ScanCallback) field.get(central);

    // Fake scan result
    ScanResult scanResult = mock(ScanResult.class);
    BluetoothDevice device = mock(BluetoothDevice.class);
    when(device.getName()).thenReturn("Polar H7");
    when(scanResult.getDevice()).thenReturn(device);
    scanCallback.onScanResult(CALLBACK_TYPE_ALL_MATCHES, scanResult);

    // See if we get it back
    ArgumentCaptor<BluetoothPeripheral> bluetoothPeripheralCaptor = ArgumentCaptor.forClass(BluetoothPeripheral.class);
    ArgumentCaptor<ScanResult> scanResultCaptor = ArgumentCaptor.forClass(ScanResult.class);
    verify(callback).onDiscoveredPeripheral(bluetoothPeripheralCaptor.capture(), scanResultCaptor.capture());

    assertEquals(scanResultCaptor.getValue(), scanResult);
    assertEquals(bluetoothPeripheralCaptor.getValue().getName(), "Polar H7");
}
 
Example #22
Source Project: blessed-android   Author: weliem   File: BluetoothCentralTest.java    License: MIT License 5 votes vote down vote up
@Test
public void scanFailedTest() throws Exception {
    application.grantPermissions(Manifest.permission.ACCESS_COARSE_LOCATION);
    central.scanForPeripherals();
    verify(scanner).startScan(anyList(), any(ScanSettings.class), any(ScanCallback.class));

    // Grab the scan callback that is used
    Field field = BluetoothCentral.class.getDeclaredField("scanByServiceUUIDCallback");
    field.setAccessible(true);
    ScanCallback scanCallback = (ScanCallback) field.get(central);

    scanCallback.onScanFailed(SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES);

    verify(callback).onScanFailed(SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES);
}
 
Example #23
Source Project: blessed-android   Author: weliem   File: BluetoothCentralTest.java    License: MIT License 5 votes vote down vote up
@Test
public void autoconnectTestUnCached() throws Exception {
    application.grantPermissions(Manifest.permission.ACCESS_COARSE_LOCATION);

    BluetoothDevice device = mock(BluetoothDevice.class);
    when(device.getAddress()).thenReturn("12:23:34:98:76:54");
    when(device.getType()).thenReturn(BluetoothDevice.DEVICE_TYPE_LE);
    bluetoothAdapter.addDevice(device);

    BluetoothPeripheral peripheral = mock(BluetoothPeripheral.class);
    when(peripheral.getAddress()).thenReturn("12:23:34:98:76:54");
    when(peripheral.getType()).thenReturn(BluetoothDevice.DEVICE_TYPE_UNKNOWN);
    central.autoConnectPeripheral(peripheral, peripheralCallback);

    verify(peripheral, never()).autoConnect();
    verify(scanner).startScan(anyList(), any(ScanSettings.class), any(ScanCallback.class));

    // Grab the scan callback that is used
    Field field = BluetoothCentral.class.getDeclaredField("autoConnectScanCallback");
    field.setAccessible(true);
    ScanCallback scanCallback = (ScanCallback) field.get(central);

    // Fake scan result
    ScanResult scanResult = mock(ScanResult.class);
    when(scanResult.getDevice()).thenReturn(device);
    scanCallback.onScanResult(CALLBACK_TYPE_ALL_MATCHES, scanResult);

    verify(peripheral).connect();
}
 
Example #24
Source Project: blessed-android   Author: weliem   File: BluetoothCentralTest.java    License: MIT License 5 votes vote down vote up
@Test
public void bluetoothOffTest() {
    application.grantPermissions(Manifest.permission.ACCESS_COARSE_LOCATION);
    bluetoothAdapter.setEnabled(false);
    central.scanForPeripherals();
    verify(scanner, never()).startScan(anyList(), any(ScanSettings.class), any(ScanCallback.class));
}
 
Example #25
Source Project: bitgatt   Author: Fitbit   File: BitgattLeScanner.java    License: Mozilla Public License 2.0 5 votes vote down vote up
@Override
public void startScan(List<ScanFilter> filters, ScanSettings settings, ScanCallback callback) {
    if(leScanner == null) {
        Timber.w("The scanner was null, context or adapter was null");
        return;
    }
    leScanner.startScan(filters, settings, callback);
}
 
Example #26
Source Project: bluetooth   Author: JimSeker   File: DiscoverFragment.java    License: Apache License 2.0 5 votes vote down vote up
void start_discover() {

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

        ScanFilter filter = new ScanFilter.Builder()
            .setServiceUuid(new ParcelUuid(UUID.fromString(getString(R.string.blue_uuid))))
            .build();
        filters.add(filter);

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

        mBluetoothLeScanner.startScan(filters, settings, mScanCallback);

        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mBluetoothLeScanner.stopScan(mScanCallback);
                logthis("Discovery stopped");
                discovering = false;
                discover.setText("Start Discovering");
            }
        }, 5000);
        logthis("Discovery started");
        discovering = true;
        discover.setText("Stop Discovering");
    }
 
Example #27
Source Project: bitgatt   Author: Fitbit   File: PeripheralScanner.java    License: Mozilla Public License 2.0 5 votes vote down vote up
/**
 * This will start a high priority scan
 *
 * @return true if scan started, false if not
 */
synchronized boolean startHighPriorityScan(@Nullable Context context) {
    if (context == null) {
        Timber.v("Can't start a high priority scan with a null context");
        return false;
    }
    if (isScanning.get()) {
        cancelScan(context);
    }
    Timber.d("Start High priority Scan");
    scanMode = ScanSettings.SCAN_MODE_LOW_LATENCY;
    return startScan(context);
}
 
Example #28
Source Project: SweetBlue   Author: iDevicesInc   File: L_Util.java    License: GNU General Public License v3.0 5 votes vote down vote up
static void startScan(BluetoothAdapter adapter, ScanSettings scanSettings, ScanCallback listener) {
    m_UserScanCallback = listener;
    // Add a last ditch check to make sure the adapter isn't null before trying to start the scan.
    // We check in the task, but by the time we reach this method, it could have been shut off
    // Either the adapter, or the scanner object may be null, so we check it here
    if (adapter == null || adapter.getBluetoothLeScanner() == null)
    {
        m_callback.onScanFailed(android.bluetooth.le.ScanCallback.SCAN_FAILED_INTERNAL_ERROR);
        return;
    }
    adapter.getBluetoothLeScanner().startScan(getFilterList(), scanSettings, m_callback);
}
 
Example #29
Source Project: bitgatt   Author: Fitbit   File: MockLollipopScanner.java    License: Mozilla Public License 2.0 5 votes vote down vote up
public void startScan(int mScannerId, ScanSettings mSettings, List<ScanFilter> mFilters, List<List<ResultStorageDescriptor>> mResultStorages, String packageName) {
    if (mSettings.getScanMode() == ScanSettings.SCAN_MODE_LOW_LATENCY) {
        currentScanState = ScanState.LOW_LATENCY;
    } else if (mSettings.getScanMode() == ScanSettings.SCAN_MODE_BALANCED) {
        currentScanState = ScanState.BALANCED_LATENCY;
    } else if (mSettings.getScanMode() == ScanSettings.SCAN_MODE_LOW_POWER) {
        currentScanState = ScanState.HIGH_LATENCY;
    }
    Timber.v("Current scan state: %s", currentScanState);
    SystemClock.sleep(TIME_BETWEEN_RESULTS);
    resultsRunnable.run();
}
 
Example #30
Source Project: bitgatt   Author: Fitbit   File: MockLollipopScanner.java    License: Mozilla Public License 2.0 5 votes vote down vote up
private boolean isSettingsConfigAllowedForScan(ScanSettings settings) {

        final int callbackType = settings.getCallbackType();
        // Only support regular scan if no offloaded filter support.
        if (callbackType == ScanSettings.CALLBACK_TYPE_ALL_MATCHES
            && settings.getReportDelayMillis() == 0) {
            return true;
        }
        return false;
    }