Java Code Examples for android.bluetooth.le.ScanCallback
The following examples show how to use
android.bluetooth.le.ScanCallback.
These examples are extracted from open source projects.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: android_9.0.0_r45 Author: lulululbj File: BluetoothAdapter.java License: Apache License 2.0 | 8 votes |
/** * Stops an ongoing Bluetooth LE device scan. * * @param callback used to identify which scan to stop must be the same handle used to start the * scan * @deprecated Use {@link BluetoothLeScanner#stopScan(ScanCallback)} instead. */ @Deprecated @RequiresPermission(Manifest.permission.BLUETOOTH_ADMIN) public void stopLeScan(LeScanCallback callback) { if (DBG) { Log.d(TAG, "stopLeScan()"); } BluetoothLeScanner scanner = getBluetoothLeScanner(); if (scanner == null) { return; } synchronized (mLeScanClients) { ScanCallback scanCallback = mLeScanClients.remove(callback); if (scanCallback == null) { if (DBG) { Log.d(TAG, "scan not started yet"); } return; } scanner.stopScan(scanCallback); } }
Example #2
Source Project: blessed-android Author: weliem File: BluetoothCentral.java License: MIT License | 6 votes |
/** * 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: blessed-android Author: weliem File: BluetoothCentralTest.java License: MIT License | 6 votes |
@Test public void scanForPeripheralsTest() 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); // Fake scan result ScanResult scanResult = mock(ScanResult.class); BluetoothDevice device = mock(BluetoothDevice.class); when(device.getAddress()).thenReturn("00:00:00:00"); 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().getAddress(), "00:00:00:00"); }
Example #4
Source Project: blessed-android Author: weliem File: BluetoothCentralTest.java License: MIT License | 6 votes |
@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 #5
Source Project: blessed-android Author: weliem File: BluetoothCentralTest.java License: MIT License | 6 votes |
@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 #6
Source Project: bitgatt Author: Fitbit File: MockLollipopScanner.java License: Mozilla Public License 2.0 | 6 votes |
/** * Stops an ongoing Bluetooth LE scan. * * @param callback */ public void stopScan(ScanCallback callback) { if (!BluetoothAdapter.getAdapterState()) { throw new IllegalStateException("Bluetooth off"); } synchronized (mLeScanClients) { BleScanCallbackWrapper wrapper = mLeScanClients.remove(callback); if (wrapper == null) { if (DBG) Log.d(TAG, "could not find callback wrapper"); return; } wrapper.stopLeScan(); } }
Example #7
Source Project: bitgatt Author: Fitbit File: MockLollipopScanner.java License: Mozilla Public License 2.0 | 6 votes |
/** * Flush pending batch scan results stored in Bluetooth controller. This will return Bluetooth * LE scan results batched on bluetooth controller. Returns immediately, batch scan results data * will be delivered through the {@code callback}. * * @param callback Callback of the Bluetooth LE Scan, it has to be the same instance as the one * used to start scan. */ public void flushPendingScanResults(ScanCallback callback) { if (!BluetoothAdapter.getAdapterState()) { throw new IllegalStateException("Bluetooth off"); } if (callback == null) { throw new IllegalArgumentException("callback cannot be null!"); } synchronized (mLeScanClients) { BleScanCallbackWrapper wrapper = mLeScanClients.get(callback); if (wrapper == null) { return; } wrapper.flushPendingBatchResults(); } }
Example #8
Source Project: bitgatt Author: Fitbit File: MockLollipopScanner.java License: Mozilla Public License 2.0 | 6 votes |
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 #9
Source Project: bitgatt Author: Fitbit File: MockLollipopScanner.java License: Mozilla Public License 2.0 | 6 votes |
public void startRegistration() { synchronized (this) { // Scan stopped. if (mScannerId == -1 || mScannerId == -2) return; try { mBluetoothGatt.registerScanner(this, mWorkSource); wait(REGISTRATION_CALLBACK_TIMEOUT_MILLIS); } catch (InterruptedException e) { Timber.tag(TAG).e(e, "application registration exception"); postCallbackError(mScanCallback, ScanCallback.SCAN_FAILED_INTERNAL_ERROR); } if (mScannerId > 0) { mLeScanClients.put(mScanCallback, this); } else { // Registration timed out or got exception, reset RscannerId to -1 so no // subsequent operations can proceed. if (mScannerId == 0) mScannerId = -1; // If scanning too frequently, don't report anything to the app. if (mScannerId == -2) return; postCallbackError(mScanCallback, ScanCallback.SCAN_FAILED_APPLICATION_REGISTRATION_FAILED); } } }
Example #10
Source Project: bitgatt Author: Fitbit File: MockLollipopScanner.java License: Mozilla Public License 2.0 | 6 votes |
private int postCallbackErrorOrReturn(final ScanCallback callback, final int errorCode) { if (callback == null) { return errorCode; } else { postCallbackError(callback, errorCode); return 0; } }
Example #11
Source Project: android_9.0.0_r45 Author: lulululbj File: BluetoothAdapter.java License: Apache License 2.0 | 6 votes |
/** * Use {@link #getDefaultAdapter} to get the BluetoothAdapter instance. */ BluetoothAdapter(IBluetoothManager managerService) { if (managerService == null) { throw new IllegalArgumentException("bluetooth manager service is null"); } try { mServiceLock.writeLock().lock(); mService = managerService.registerAdapter(mManagerCallback); } catch (RemoteException e) { Log.e(TAG, "", e); } finally { mServiceLock.writeLock().unlock(); } mManagerService = managerService; mLeScanClients = new HashMap<LeScanCallback, ScanCallback>(); mToken = new Binder(); }
Example #12
Source Project: attach Author: gluonhq File: DalvikBleService.java License: GNU General Public License v3.0 | 6 votes |
private ScanCallback createDeviceCallback() { return new ScanCallback() { @Override public void onScanResult(int callbackType, ScanResult result) { BluetoothDevice device = result.getDevice(); if (devices.values().contains(device)) { return; } String address = device.getAddress(); String name = device.getName(); devices.put(address, device); if (debug) { Log.v(TAG, "BLE discovered device: " + device + " with name: " + name + " and address: " + address); } scanDeviceDetected(name, address); } }; }
Example #13
Source Project: RxCentralBle Author: uber File: ThrottledLollipopScannerTest.java License: Apache License 2.0 | 6 votes |
@Test public void scan_failed_onCallback() { when(bluetoothAdapter.isEnabled()).thenReturn(true); when(BluetoothAdapter.getDefaultAdapter()).thenReturn(bluetoothAdapter); scanDataTestObserver = scanner.scan().test(); testScheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS); ArgumentCaptor<ScanCallback> argument = ArgumentCaptor.forClass(ScanCallback.class); verify(bluetoothLeScanner).startScan(any(), any(), argument.capture()); argument.getValue().onScanFailed(0); scanDataTestObserver.assertError( throwable -> { ConnectionError error = (ConnectionError) throwable; return error != null && error.getCode() == ConnectionError.Code.SCAN_FAILED; }); }
Example #14
Source Project: RxCentralBle Author: uber File: LollipopScannerTest.java License: Apache License 2.0 | 6 votes |
@Test public void scan_failed_onCallback() { when(bluetoothAdapter.isEnabled()).thenReturn(true); when(BluetoothAdapter.getDefaultAdapter()).thenReturn(bluetoothAdapter); scanDataTestObserver = scanner.scan().test(); ArgumentCaptor<ScanCallback> argument = ArgumentCaptor.forClass(ScanCallback.class); verify(bluetoothLeScanner).startScan(any(), any(), argument.capture()); argument.getValue().onScanFailed(0); scanDataTestObserver.assertError( throwable -> { ConnectionError error = (ConnectionError) throwable; return error != null && error.getCode() == ConnectionError.Code.SCAN_FAILED; }); }
Example #15
Source Project: EFRConnect-android Author: SiliconLabs File: BlueToothService.java License: Apache License 2.0 | 6 votes |
private void stopDiscovery() { if (bluetoothAdapter == null) { return; } if (useBLE) { if (bluetoothAdapter.getBluetoothLeScanner() == null) { return; } if (bleScannerCallback != null) { bluetoothAdapter.getBluetoothLeScanner().stopScan((ScanCallback) bleScannerCallback); } } else if (bluetoothAdapter.isDiscovering()) { bluetoothAdapter.cancelDiscovery(); } }
Example #16
Source Project: RxAndroidBle Author: Polidea File: ScanOperationApi21.java License: Apache License 2.0 | 6 votes |
@BleScanException.Reason static int errorCodeToBleErrorCode(int errorCode) { switch (errorCode) { case ScanCallback.SCAN_FAILED_ALREADY_STARTED: return BleScanException.SCAN_FAILED_ALREADY_STARTED; case ScanCallback.SCAN_FAILED_APPLICATION_REGISTRATION_FAILED: return BleScanException.SCAN_FAILED_APPLICATION_REGISTRATION_FAILED; case ScanCallback.SCAN_FAILED_FEATURE_UNSUPPORTED: return BleScanException.SCAN_FAILED_FEATURE_UNSUPPORTED; case ScanCallback.SCAN_FAILED_INTERNAL_ERROR: return BleScanException.SCAN_FAILED_INTERNAL_ERROR; case 5: // ScanCallback.SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES return BleScanException.SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES; default: RxBleLog.w("Encountered unknown scanning error code: %d -> check android.bluetooth.le.ScanCallback"); return BleScanException.UNKNOWN_ERROR_CODE; } }
Example #17
Source Project: RxAndroidBle Author: Polidea File: RxBleAdapterWrapper.java License: Apache License 2.0 | 6 votes |
@TargetApi(21 /* Build.VERSION_CODES.LOLLIPOP */) public void stopLeScan(ScanCallback scanCallback) { if (!bluetoothAdapter.isEnabled()) { // this situation seems to be a problem since API 29 RxBleLog.v( "BluetoothAdapter is disabled, calling BluetoothLeScanner.stopScan(ScanCallback) may cause IllegalStateException" ); // if stopping the scan is not possible due to BluetoothAdapter turned off then it is probably stopped anyway return; } final BluetoothLeScanner bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner(); if (bluetoothLeScanner == null) { RxBleLog.w( "Cannot call BluetoothLeScanner.stopScan(ScanCallback) on 'null' reference; BluetoothAdapter.isEnabled() == %b", bluetoothAdapter.isEnabled() ); // if stopping the scan is not possible due to BluetoothLeScanner not accessible then it is probably stopped anyway // this should not happen since the check for BluetoothAdapter.isEnabled() has been added above. This situation was only // observed when the adapter was disabled return; } bluetoothLeScanner.stopScan(scanCallback); }
Example #18
Source Project: blessed-android Author: weliem File: BluetoothCentral.java License: MIT License | 5 votes |
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 #19
Source Project: blessed-android Author: weliem File: BluetoothCentralTest.java License: MIT License | 5 votes |
@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 #20
Source Project: blessed-android Author: weliem File: BluetoothCentralTest.java License: MIT License | 5 votes |
@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 #21
Source Project: blessed-android Author: weliem File: BluetoothCentralTest.java License: MIT License | 5 votes |
@Test public void scanFailedAutoconnectTest() throws Exception { // Grab the scan callback that is used Field field = BluetoothCentral.class.getDeclaredField("autoConnectScanCallback"); 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 #22
Source Project: blessed-android Author: weliem File: BluetoothCentralTest.java License: MIT License | 5 votes |
@Test public void scanForNamesFailedTest() throws Exception { application.grantPermissions(Manifest.permission.ACCESS_COARSE_LOCATION); String myName = "Polar"; central.scanForPeripheralsWithNames(new String[]{myName}); // Grab the scan callback that is used Field field = BluetoothCentral.class.getDeclaredField("scanByNameCallback"); 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 |
@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 |
@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 |
@Override public void startScan(ScanCallback callback) { if(leScanner == null) { Timber.w("The scanner was null, context or adapter was null"); return; } leScanner.startScan(callback); }
Example #26
Source Project: bitgatt Author: Fitbit File: BitgattLeScanner.java License: Mozilla Public License 2.0 | 5 votes |
@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 #27
Source Project: bitgatt Author: Fitbit File: BitgattLeScanner.java License: Mozilla Public License 2.0 | 5 votes |
@TargetApi(Build.VERSION_CODES.O) @Override public int startScan(@Nullable List<ScanFilter> filters, @Nullable ScanSettings settings, @NonNull PendingIntent callbackIntent) { if(leScanner == null || !FitbitGatt.atLeastSDK(Build.VERSION_CODES.O)) { Timber.w("The scanner was null, context or adapter was null"); return ScanCallback.SCAN_FAILED_INTERNAL_ERROR; } return leScanner.startScan(filters, settings, callbackIntent); }
Example #28
Source Project: bitgatt Author: Fitbit File: BitgattLeScanner.java License: Mozilla Public License 2.0 | 5 votes |
@Override public void stopScan(ScanCallback callback) { if(leScanner == null) { Timber.w("The scanner was null, context or adapter was null"); return; } leScanner.stopScan(callback); }
Example #29
Source Project: bitgatt Author: Fitbit File: BitgattLeScanner.java License: Mozilla Public License 2.0 | 5 votes |
@Override public void flushPendingScanResults(ScanCallback callback) { if(leScanner == null) { Timber.w("The scanner was null, the context or adpater also must have been null"); return; } leScanner.flushPendingScanResults(callback); }
Example #30
Source Project: bitgatt Author: Fitbit File: MockLollipopScanner.java License: Mozilla Public License 2.0 | 5 votes |
/** * Use {@link BluetoothAdapter#getBluetoothLeScanner()} instead. * */ public MockLollipopScanner() { Looper mockMainThreadLooper = mock(Looper.class); Thread mockMainThread = mock(Thread.class); when(mockMainThread.getName()).thenReturn("Irvin's mock thread"); when(mockMainThreadLooper.getThread()).thenReturn(mockMainThread); mockHandler = mock(Handler.class); doAnswer(handlerPostAnswer).when(mockHandler).post(any(Runnable.class)); doAnswer(handlerPostAnswer).when(mockHandler).postDelayed(any(Runnable.class), anyLong()); when(mockHandler.getLooper()).thenReturn(mockMainThreadLooper); mHandler = mockHandler; mLeScanClients = new HashMap<ScanCallback, BleScanCallbackWrapper>(); }