Java Code Examples for android.bluetooth.le.ScanFilter

The following examples show how to use android.bluetooth.le.ScanFilter. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: blessed-android   Source File: BluetoothCentral.java    License: MIT License 7 votes vote down vote up
/**
 * Scan for peripherals that have any of the specified peripheral mac addresses.
 *
 * @param peripheralAddresses array of peripheral mac addresses to scan for
 */
public void scanForPeripheralsWithAddresses(final String[] peripheralAddresses) {
    List<ScanFilter> filters = null;
    if (peripheralAddresses != null) {
        filters = new ArrayList<>();
        for (String address : peripheralAddresses) {
            if (BluetoothAdapter.checkBluetoothAddress(address)) {
                ScanFilter filter = new ScanFilter.Builder()
                        .setDeviceAddress(address)
                        .build();
                filters.add(filter);
            } else {
                Timber.e("%s is not a valid address. Make sure all alphabetic characters are uppercase.", address);
            }
        }
    }

    startScan(filters, scanSettings, scanByServiceUUIDCallback);
}
 
Example 2
Source Project: blessed-android   Source File: BluetoothCentral.java    License: MIT License 6 votes vote down vote up
/**
 * Set scan timeout timer, timeout time is {@code SCAN_TIMEOUT}.
 * If timeout is executed the scan is stopped and automatically restarted. This is done to avoid Android 9 scan restrictions
 */
private void setScanTimer() {
    cancelTimeoutTimer();

    timeoutRunnable = new Runnable() {
        @Override
        public void run() {
            Timber.d("scanning timeout, restarting scan");
            final ScanCallback callback = currentCallback;
            final List<ScanFilter> filters = currentFilters;
            stopScan();

            // Restart the scan and timer
            callBackHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    startScan(filters, scanSettings, callback);
                }
            }, SCAN_RESTART_DELAY);
        }
    };

    mainHandler.postDelayed(timeoutRunnable, SCAN_TIMEOUT);
}
 
Example 3
Source Project: nearby-beacons   Source 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 4
Source Project: bitgatt   Source File: PeripheralScannerTest.java    License: Mozilla Public License 2.0 6 votes vote down vote up
@Test
public void testStartPendingIntentScanNotPeriodicalScan() {
    assertFalse(FitbitGatt.getInstance().getPeripheralScanner().isScanning());
    assertFalse(FitbitGatt.getInstance().getPeripheralScanner().isPendingIntentScanning());
    FitbitGatt.getInstance().getPeripheralScanner().setDeviceNameFilters(names);
    ArrayList<ScanFilter> filters = new ArrayList<>();
    for (String name : names) {
        filters.add(new ScanFilter.Builder().setDeviceName(name).build());
    }
    FitbitGatt.getInstance().getPeripheralScanner().startPendingIntentBasedBackgroundScan(filters, appContext);
    CountDownLatch cdl = new CountDownLatch(1);
    handler.postDelayed(() -> {
        assertFalse(FitbitGatt.getInstance().getPeripheralScanner().isScanning());
        cdl.countDown();
    }, 300);
    verifyCountDown(cdl);
}
 
Example 5
Source Project: bitgatt   Source File: PeripheralScannerTest.java    License: Mozilla Public License 2.0 6 votes vote down vote up
@Test
public void testStartPendingIntentScanNotHighPriorityScan() {
    assertFalse(FitbitGatt.getInstance().getPeripheralScanner().isScanning());
    assertFalse(FitbitGatt.getInstance().getPeripheralScanner().isPendingIntentScanning());
    FitbitGatt.getInstance().getPeripheralScanner().setDeviceNameFilters(names);
    ArrayList<ScanFilter> filters = new ArrayList<>();
    for (String name : names) {
        filters.add(new ScanFilter.Builder().setDeviceName(name).build());
    }
    FitbitGatt.getInstance().getPeripheralScanner().startPendingIntentBasedBackgroundScan(filters, appContext);
    CountDownLatch cdl = new CountDownLatch(1);
    handler.postDelayed(() -> {
        assertFalse(FitbitGatt.getInstance().getPeripheralScanner().isScanning());
        cdl.countDown();
    }, 300);
    verifyCountDown(cdl);
}
 
Example 6
Source Project: bitgatt   Source 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 7
Source Project: android_9.0.0_r45   Source File: BluetoothLeDeviceFilter.java    License: Apache License 2.0 6 votes vote down vote up
private BluetoothLeDeviceFilter(Pattern namePattern, ScanFilter scanFilter,
        byte[] rawDataFilter, byte[] rawDataFilterMask, String renamePrefix,
        String renameSuffix, int renameBytesFrom, int renameBytesLength,
        int renameNameFrom, int renameNameLength, boolean renameBytesReverseOrder) {
    mNamePattern = namePattern;
    mScanFilter = ObjectUtils.firstNotNull(scanFilter, ScanFilter.EMPTY);
    mRawDataFilter = rawDataFilter;
    mRawDataFilterMask = rawDataFilterMask;
    mRenamePrefix = renamePrefix;
    mRenameSuffix = renameSuffix;
    mRenameBytesFrom = renameBytesFrom;
    mRenameBytesLength = renameBytesLength;
    mRenameNameFrom = renameNameFrom;
    mRenameNameLength = renameNameLength;
    mRenameBytesReverseOrder = renameBytesReverseOrder;
}
 
Example 8
Source Project: esp-idf-provisioning-android   Source File: BleScanner.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This method is used to start BLE scan.
 */
@RequiresPermission(allOf = {Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN})
public void startScan() {

    if (!bluetoothAdapter.isEnabled()) {
        bleScanListener.scanStartFailed();
        return;
    }
    Log.d(TAG, "Starting BLE device scanning...");

    bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
    List<ScanFilter> filters = new ArrayList<>();
    ScanSettings settings = new ScanSettings.Builder()
            .setScanMode(ScanSettings.SCAN_MODE_BALANCED)
            .build();

    isScanning = true;
    bluetoothLeScanner.startScan(filters, settings, scanCallback);
    handler.postDelayed(stopScanTask, SCAN_TIME_OUT);
}
 
Example 9
Source Project: EFRConnect-android   Source File: ScanFilterCompat.java    License: Apache License 2.0 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public ScanFilter createScanFilter() {
    ScanFilter.Builder builder = new ScanFilter.Builder()
            .setDeviceAddress(deviceAddress)
            .setDeviceName(deviceName);

    if (serviceUuid != null) {
        builder.setServiceUuid(serviceUuid, serviceUuidMask);
    }
    if (serviceDataUuid != null) {
        builder.setServiceData(serviceDataUuid, serviceData, serviceDataMask);
    }
    if (manufacturerId >= 0) {
        builder.setManufacturerData(manufacturerId, manufacturerData, manufacturerDataMask);
    }

    return builder.build();
}
 
Example 10
Source Project: xDrip   Source 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 11
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 12
Source Project: AndroidBleManager   Source File: ScanFilterCompat.java    License: Apache License 2.0 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public ScanFilter toApi21() {
    ScanFilter.Builder builder = new ScanFilter.Builder();
    if (mDeviceName != null) {
        builder.setDeviceName(mDeviceName);
    }
    if (mServiceUuid != null) {
        builder.setServiceUuid(mServiceUuid, mServiceUuidMask);
    }
    if (mDeviceAddress != null) {
        builder.setDeviceAddress(mDeviceAddress);
    }
    if (mServiceDataUuid != null) {
        builder.setServiceData(mServiceDataUuid, mServiceData, mServiceDataMask);
    }
    if (mManufacturerId < 0) {
        builder.setManufacturerData(mManufacturerId, mManufacturerData, mManufacturerDataMask);
    }
    return builder.build();
}
 
Example 13
Source Project: AndroidDemoProjects   Source 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 14
Source Project: connectivity-samples   Source File: ScannerFragment.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Return a List of {@link ScanFilter} objects to filter by Service UUID.
 */
private List<ScanFilter> buildScanFilters() {
    List<ScanFilter> scanFilters = new ArrayList<>();

    ScanFilter.Builder builder = new ScanFilter.Builder();
    // Comment out the below line to see all BLE devices around you
    builder.setServiceUuid(Constants.Service_UUID);
    scanFilters.add(builder.build());

    return scanFilters;
}
 
Example 15
Source Project: blessed-android   Source File: BluetoothCentral.java    License: MIT License 5 votes vote down vote up
private void startScan(List<ScanFilter> filters, ScanSettings scanSettings, ScanCallback scanCallback) {
    // Check is BLE is available, enabled and all permission granted
    if (!isBleReady()) return;

    // Make sure we are not already scanning, we only want one scan at the time
    if (isScanning()) {
        Timber.e("other scan still active, stopping scan");
        stopScan();
    }

    // Get a new scanner object
    if (bluetoothScanner == null) {
        bluetoothScanner = bluetoothAdapter.getBluetoothLeScanner();
    }

    // If get scanner was succesful, start the scan
    if (bluetoothScanner != null) {
        // Start the scanner
        setScanTimer();
        currentCallback = scanCallback;
        currentFilters = filters;
        bluetoothScanner.startScan(filters, scanSettings, scanCallback);
        Timber.i("scan started");
    } else {
        Timber.e("starting scan failed");
    }
}
 
Example 16
Source Project: blessed-android   Source File: BluetoothCentral.java    License: MIT License 5 votes vote down vote up
/**
 * Scan for peripherals that advertise at least one of the specified service UUIDs.
 *
 * @param serviceUUIDs an array of service UUIDs
 */
public void scanForPeripheralsWithServices(final UUID[] serviceUUIDs) {
    currentFilters = null;
    if (serviceUUIDs != null) {
        currentFilters = new ArrayList<>();
        for (UUID serviceUUID : serviceUUIDs) {
            ScanFilter filter = new ScanFilter.Builder()
                    .setServiceUuid(new ParcelUuid(serviceUUID))
                    .build();
            currentFilters.add(filter);
        }
    }

    startScan(currentFilters, scanSettings, scanByServiceUUIDCallback);
}
 
Example 17
Source Project: blessed-android   Source File: BluetoothCentral.java    License: MIT License 5 votes vote down vote up
/**
 * Scan for peripherals that need to be autoconnected but are not cached
 */
private void scanForAutoConnectPeripherals() {
    // Check is BLE is available, enabled and all permission granted
    if (!isBleReady()) return;

    // Stop previous autoconnect scans if any
    if (autoConnectScanner != null) {
        stopAutoconnectScan();
    }

    // Start the scanner
    autoConnectScanner = bluetoothAdapter.getBluetoothLeScanner();
    if (autoConnectScanner != null) {
        List<ScanFilter> filters;
        filters = new ArrayList<>();
        for (String address : reconnectPeripheralAddresses) {
            ScanFilter filter = new ScanFilter.Builder()
                    .setDeviceAddress(address)
                    .build();
            filters.add(filter);
        }

        // Start the scanner
        autoConnectScanner.startScan(filters, autoConnectScanSettings, autoConnectScanCallback);
        Timber.d("started scanning to autoconnect peripherals (" + reconnectPeripheralAddresses.size() + ")");
        setAutoConnectTimer();
    } else {
        Timber.e("starting autoconnect scan failed");
    }
}
 
Example 18
Source Project: blessed-android   Source 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 19
Source Project: bitgatt   Source 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 20
Source Project: android_wear_for_ios   Source File: MusicControlActivity.java    License: MIT License 5 votes vote down vote up
@TargetApi(21)
    private List<ScanFilter> create_scan_filter(){
//        ScanFilter filter = new ScanFilter.Builder().setServiceUuid(ParcelUuid.fromString(service_ancs)).build();
        ScanFilter filter = new ScanFilter.Builder().setServiceUuid(ParcelUuid.fromString(service_ams)).build();
        List<ScanFilter> list = new ArrayList<ScanFilter>(1);
        list.add(filter);
        return list;
    }
 
Example 21
Source Project: bitgatt   Source File: PeripheralScanner.java    License: Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Can be used if directly managing scan filters is required
 *
 * @param scanFilters The scan filters to be applied to the scan
 */

void setScanFilters(List<ScanFilter> scanFilters) {
    synchronized (this.scanFilters) {
        this.scanFilters.clear();
        this.scanFilters.addAll(scanFilters);
    }
}
 
Example 22
Source Project: bitgatt   Source File: PeripheralScanner.java    License: Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Set Filters by device name, will clear and reset the filters such that the next periodical
 * or high priority scan will pick them up
 *
 * @param deviceNameFilters The bluetooth peripheral names to limit the filter for
 */
void setDeviceNameFilters(List<String> deviceNameFilters) {
    synchronized (scanFilters) {
        scanFilters.clear();
        if (deviceNameFilters != null) {
            for (String name : deviceNameFilters) {
                scanFilters.add(new ScanFilter.Builder().setDeviceName(name).build());
            }
        }
    }
}
 
Example 23
Source Project: bitgatt   Source File: PeripheralScanner.java    License: Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Set filters by UUID, will clear and reset the filters such that the next periodical
 * or high priority scan will pick them up
 *
 * @param uuidFilters The list of service UUIDs to use in the filter
 */
void setServiceUuidFilters(List<ParcelUuid> uuidFilters) {
    synchronized (scanFilters) {
        scanFilters.clear();
        if (uuidFilters != null) {
            for (ParcelUuid uuid : uuidFilters) {
                if (uuid != null) {
                    scanFilters.add(new ScanFilter.Builder().setServiceUuid(uuid).build());
                }
            }
        }
    }
}
 
Example 24
Source Project: bitgatt   Source File: PeripheralScanner.java    License: Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Will add a new device name to the filter list such that the next scan will find devices
 * with this name, will not affect the currently in progress scan
 *
 * @param deviceName The remote bluetooth name of the device for which you are searching
 */

void addDeviceNameFilter(String deviceName) {
    ScanFilter scanFilter = new ScanFilter.Builder().setDeviceName(deviceName).build();
    synchronized (scanFilters) {
        scanFilters.add(scanFilter);
    }
}
 
Example 25
Source Project: bitgatt   Source File: PeripheralScanner.java    License: Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Will add the service UUID with a given mask to find multiple devices that conform to a uuid
 * service pattern in the advertisement
 *
 * @param service The service parceluuid
 * @param mask    The parceluuid service mask
 */

void addServiceUUIDWithMask(ParcelUuid service, ParcelUuid mask) {
    ScanFilter scanFilter = new ScanFilter.Builder().setServiceUuid(service, mask).build();
    synchronized (scanFilters) {
        scanFilters.add(scanFilter);
    }
}
 
Example 26
Source Project: bluetooth   Source 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   Source File: AlwaysConnectedScanner.java    License: Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Will add a list of filters to the existing set of filters, will not check for duplicates
 * and will not clear the existing filter set.  This method will only change the current set of
 * filters once every 30s so if you call this method multiple times, the changes will be spread
 * over 30s x n calls.
 *
 * @param context The android context
 * @param filters The list of filters
 */
public synchronized void addScanFilters(@NonNull Context context, @NonNull List<ScanFilter> filters) {
    scanFilters.addAll(filters);
    if (FitbitGatt.getInstance().getPeripheralScanner() != null) {
        FitbitGatt.getInstance().getPeripheralScanner().setScanFilters(scanFilters);
    }
    // let's only change this once per scan too much warn interval
    mainHandlerForScheduling.postDelayed(() -> {
        FitbitGatt.getInstance().getPeripheralScanner().cancelPendingIntentBasedBackgroundScan();
        FitbitGatt.getInstance().getPeripheralScanner().startPendingIntentBasedBackgroundScan(scanFilters, context);
    }, PeripheralScanner.SCAN_TOO_MUCH_WARN_INTERVAL);
}
 
Example 28
Source Project: bitgatt   Source File: AlwaysConnectedScanner.java    License: Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Will append a new scan filter to the set of scan filters, will restart the internal
 * background scanner to ensure that the new filter is picked up.  Since we want to always
 * avoid the scan-too-much no-op for our scanner, we will only change this once per 30s.
 * <p>
 * This method will only change the current set of
 * filters once every 30s so if you call this method multiple times, the changes will be spread
 * over 30s x n calls.
 *
 * @param context    The android context
 * @param scanFilter The new scan filter to add
 */

public synchronized void addScanFilter(@NonNull Context context, @NonNull ScanFilter scanFilter) {
    if (!scanFilters.contains(scanFilter)) {
        scanFilters.add(scanFilter);
    }
    if (FitbitGatt.getInstance().getPeripheralScanner() != null) {
        FitbitGatt.getInstance().getPeripheralScanner().setScanFilters(scanFilters);
    }
    // let's only change this once per scan too much warn interval
    mainHandlerForScheduling.postDelayed(() -> {
        FitbitGatt.getInstance().getPeripheralScanner().cancelPendingIntentBasedBackgroundScan();
        FitbitGatt.getInstance().getPeripheralScanner().startPendingIntentBasedBackgroundScan(scanFilters, context);
    }, PeripheralScanner.SCAN_TOO_MUCH_WARN_INTERVAL);
}
 
Example 29
Source Project: bitgatt   Source File: AlwaysConnectedScanner.java    License: Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Will remove a scan filter from the set of scan filters.
 * <p>
 * This method will only change the current set of
 * filters once every 30s so if you call this method multiple times, the changes will be spread
 * over 30s x n calls.
 *
 * @param context    The android context
 * @param scanFilter The scan filter to remove
 */

public synchronized void removeScanFilter(@NonNull Context context, @NonNull ScanFilter scanFilter) {
    if (!scanFilters.contains(scanFilter)) {
        scanFilters.remove(scanFilter);
    }
    if (FitbitGatt.getInstance().getPeripheralScanner() != null) {
        FitbitGatt.getInstance().getPeripheralScanner().setScanFilters(scanFilters);
    }
    // let's only change this once per scan too much warn interval
    mainHandlerForScheduling.postDelayed(() -> {
        FitbitGatt.getInstance().getPeripheralScanner().cancelPendingIntentBasedBackgroundScan();
        FitbitGatt.getInstance().getPeripheralScanner().startPendingIntentBasedBackgroundScan(scanFilters, context);
    }, PeripheralScanner.SCAN_TOO_MUCH_WARN_INTERVAL);
}
 
Example 30
Source Project: bitgatt   Source File: AlwaysConnectedScanner.java    License: Mozilla Public License 2.0 5 votes vote down vote up
@Override
public void onBluetoothPeripheralDisconnected(GattConnection connection) {
    // realistically we don't need to do anything here except decrement matching devices
    connection.getClientTransactionQueueController().queueTransaction(() -> {
        for (ScanFilter filter : scanFilters) {
            if (doesConnectionMatchFilter(connection, filter)) {
                int matchedDevices = numberOfMatchingConnectedDevices.get();
                if (matchedDevices > 0) {
                    matchedDevices = numberOfMatchingConnectedDevices.decrementAndGet();
                    Timber.v("Matched devices decremented to: %d", matchedDevices);
                }
            }
        }
        // if something disconnected and we are configured to continue to match, we will
        // continue scanning, if we are already scanning this will do nothing.
        int matchingDevices = numberOfMatchingConnectedDevices.get();
        if (numberOfExpectedDevices > 1 && matchingDevices < numberOfExpectedDevices) {
            Timber.v("Dropped below the number of expected devices, so we should start scanning again");
            if (FitbitGatt.getInstance().getAppContext() != null) {
                boolean didStart = continueBackgroundScanning(FitbitGatt.getInstance().getAppContext());
                if (!didStart) {
                    Timber.w("Always connected scanner tried to start scanning but failed");
                }
            }
        }
    });
}