Java Code Examples for android.bluetooth.le.BluetoothLeScanner

The following are top voted examples for showing how to use android.bluetooth.le.BluetoothLeScanner. 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: miband-android   File: MiBand.java   Source Code and License 7 votes vote down vote up
/**
 * Stops scanning for devices
 *
 * @return An Observable which emits ScanResult
 */
public Observable<ScanResult> stopScan() {
    return Observable.create(subscriber -> {
        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        if (adapter != null) {
            BluetoothLeScanner scanner = adapter.getBluetoothLeScanner();
            if (scanner != null) {
                scanner.stopScan(getScanCallback(subscriber));
            } else {
                Log.e(TAG, "BluetoothLeScanner is null");
                subscriber.onError(new NullPointerException("BluetoothLeScanner is null"));
            }
        } else {
            Log.e(TAG, "BluetoothAdapter is null");
            subscriber.onError(new NullPointerException("BluetoothLeScanner is null"));
        }
    });
}
 
Example 2
Project: TappyBLE   File: LollipopBleScanner.java   Source Code and License 6 votes vote down vote up
@Override
public void stopScan(@NonNull ScanCallback callback) {
    ScanCallbackHolder holder = callbackHolderMap.get(callback);
    if(holder == null) //possibly should throw an exception...
        return;

    BluetoothLeScanner scanner = getNativeScannerOrThrow();

    scanner.stopScan(holder.getNativeCallback());
    callbackHolderMap.remove(callback);
}
 
Example 3
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 4
Project: miband-android   File: MiBand.java   Source Code and License 6 votes vote down vote up
/**
 * Starts scanning for devices
 *
 * @return An Observable which emits ScanResult
 */
public Observable<ScanResult> startScan() {
    return Observable.create(subscriber -> {
        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        if (adapter != null) {
            BluetoothLeScanner scanner = adapter.getBluetoothLeScanner();
            if (scanner != null) {
                scanner.startScan(getScanCallback(subscriber));
            } else {
                Log.e(TAG, "BluetoothLeScanner is null");
                subscriber.onError(new NullPointerException("BluetoothLeScanner is null"));
            }
        } else {
            Log.e(TAG, "BluetoothAdapter is null");
            subscriber.onError(new NullPointerException("BluetoothLeScanner is null"));
        }
    });
}
 
Example 5
Project: NobleAries   File: Chores.java   Source Code and License 6 votes vote down vote up
private boolean startDiscoveringBle(){
	
	if (D) Log.d(TAG, "+++ startDiscoveringBle() +++");
	
	if (mAdapter.isDiscovering()){
		Log.i(TAG, "startDiscoveringBle() : Already in classic discovering mode");
		return true;
	}
	
	if (isLollipopApi){
		Log.i(TAG, "startDiscoveringBle() : Choose startScan()");
		mLeScanner = mAdapter.getBluetoothLeScanner();
		
		if (null != mLeScanner){
			((BluetoothLeScanner)mLeScanner).startScan((ScanCallback)mScanCallback);
			return true;
		}
		
		// TODO
		// return mAdapter.startScan(mScanCallback); ???
	} else {
		Log.i(TAG, "startDiscoveringBle() : Choose startLeScan()");
		return mAdapter.startLeScan(mLeScanCallback);
	}
	return true;
}
 
Example 6
Project: NobleAries   File: Chores.java   Source Code and License 6 votes vote down vote up
private boolean cancelDiscoveringBle(){
	
	if (D) Log.d(TAG, "+++ cancelDiscoveringBle() +++");
	
	if (mAdapter.isDiscovering()){
		Log.i(TAG, "cancelDiscoveringBle() : In classic discovering mode");
		return false;
	}
	
	if (isLollipopApi){
		Log.i(TAG, "cancelDiscoveringBle() : Choose stopScan()");
		
		if (null != mLeScanner){
			((BluetoothLeScanner)mLeScanner).stopScan((ScanCallback)mScanCallback);
			return true;
		}
		
		// TODO
		// return mAdapter.stopScan(mScanCallback); ???
	} else {
		Log.i(TAG, "cancelDiscoveringBle() : Choose stopLeScan()");
		mAdapter.stopLeScan(mLeScanCallback);
	}
	return true;
}
 
Example 7
Project: Android-Scanner-Compat-Library   File: BluetoothLeScannerImplLollipop.java   Source Code and License 6 votes vote down vote up
@Override
@RequiresPermission(allOf = {Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.BLUETOOTH})
/* package */ void startScanInternal(final List<ScanFilter> filters, final ScanSettings settings, final ScanCallback callback) {
	BluetoothLeUtils.checkAdapterStateOn(mBluetoothAdapter);
	offloadedFilteringSupported = mBluetoothAdapter.isOffloadedFilteringSupported();

	if (mWrappers.containsKey(callback)) {
		throw new IllegalArgumentException("scanner already started with given callback");
	}

	final BluetoothLeScanner scanner = mBluetoothAdapter.getBluetoothLeScanner();
	if (scanner == null)
		throw new IllegalStateException("BT le scanner not available");

	final ScanCallbackWrapper wrapper = new ScanCallbackWrapper(filters, settings, callback);
	final ScanCallbackImpl _callback = new ScanCallbackImpl();
	final android.bluetooth.le.ScanSettings _settings = toImpl(mBluetoothAdapter, settings);
	List<android.bluetooth.le.ScanFilter> _filters = null;
	if (filters != null && mBluetoothAdapter.isOffloadedFilteringSupported() && settings.getUseHardwareFilteringIfSupported())
		_filters = toImpl(filters);

	mWrappers.put(callback, wrapper);
	mCallbacks.put(callback, _callback);
	mWrappers2.put(_callback, wrapper);

	scanner.startScan(_filters, _settings, _callback);
}
 
Example 8
Project: Android-Scanner-Compat-Library   File: BluetoothLeScannerImplLollipop.java   Source Code and License 6 votes vote down vote up
@Override
public void stopScan(final ScanCallback callback) {
	final ScanCallbackWrapper wrapper = mWrappers.get(callback);
	if (wrapper == null)
		return;

	wrapper.close();
	mWrappers.remove(callback);
	android.bluetooth.le.ScanCallback _callback = mCallbacks.get(callback);
	mCallbacks.remove(callback);
	mWrappers2.remove(_callback);

	final BluetoothLeScanner scanner = mBluetoothAdapter.getBluetoothLeScanner();
	if (scanner == null)
		return;

	scanner.stopScan(_callback);
}
 
Example 9
Project: miband-sdk-android   File: MiBand.java   Source Code and License 6 votes vote down vote up
public static void startScan(ScanCallback callback) {
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    if (null == adapter) {
        Log.e(TAG, "BluetoothAdapter is null");
        return;
    }
    BluetoothLeScanner scanner = adapter.getBluetoothLeScanner();
    if (null == scanner) {
        Log.e(TAG, "BluetoothLeScanner is null");
        return;
    }
    scanner.startScan(callback);
}
 
Example 10
Project: miband-sdk-android   File: MiBand.java   Source Code and License 6 votes vote down vote up
public static void stopScan(ScanCallback callback) {
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    if (null == adapter) {
        Log.e(TAG, "BluetoothAdapter is null");
        return;
    }
    BluetoothLeScanner scanner = adapter.getBluetoothLeScanner();
    if (null == scanner) {
        Log.e(TAG, "BluetoothLeScanner is null");
        return;
    }
    scanner.stopScan(callback);
}
 
Example 11
Project: android-beacon-library   File: ScanHelper.java   Source Code and License 6 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.O)
void stopAndroidOBackgroundScan() {
    try {
        final BluetoothManager bluetoothManager =
                (BluetoothManager) mContext.getApplicationContext().getSystemService(Context.BLUETOOTH_SERVICE);
        BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
        if (bluetoothAdapter == null) {
            LogManager.w(TAG, "Failed to construct a BluetoothAdapter");
        } else if (!bluetoothAdapter.isEnabled()) {
            LogManager.w(TAG, "BluetoothAdapter is not enabled");
        } else {
           BluetoothLeScanner scanner =  bluetoothAdapter.getBluetoothLeScanner();
           if (scanner != null) {
               scanner.stopScan(getScanCallbackIntent());
           }
        }
    } catch (SecurityException e) {
        LogManager.e(TAG, "SecurityException stopping Android O background scanner");
    }
}
 
Example 12
Project: android-beacon-library   File: CycledLeScannerForLollipop.java   Source Code and License 6 votes vote down vote up
private BluetoothLeScanner getScanner() {
    try {
        if (mScanner == null) {
            LogManager.d(TAG, "Making new Android L scanner");
            BluetoothAdapter bluetoothAdapter = getBluetoothAdapter();
            if (bluetoothAdapter != null) {
                mScanner = getBluetoothAdapter().getBluetoothLeScanner();
            }
            if (mScanner == null) {
                LogManager.w(TAG, "Failed to make new Android L scanner");
            }
        }
    }
    catch (SecurityException e) {
        LogManager.w(TAG, "SecurityException making new Android L scanner");
    }
    return mScanner;
}
 
Example 13
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 14
Project: AndroidSensors   File: BLEMeasurementsGatherer.java   Source Code and License 5 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void addUnsuscribeCallbackFor(FlowableEmitter<SensorRecord> subscriber,
                                      final ScanCallback scanCallback){
    final BluetoothLeScanner scanner = bluetoothManager.getAdapter().getBluetoothLeScanner();
    subscriber.setCancellable(new Cancellable() {
        @Override
        public void cancel() throws Exception {
            scanner.flushPendingScanResults(scanCallback);
            scanner.stopScan(scanCallback);
        }
    });
}
 
Example 15
Project: ITagAntiLost   File: NewDevicePresenter.java   Source Code and License 5 votes vote down vote up
private void pause() {
  if (bluetoothAdapter != null) {
    BluetoothLeScanner scanner = bluetoothAdapter.getBluetoothLeScanner();
    if (scanner != null && scanCallback != null) {
      scanner.stopScan(scanCallback);
    }
  }
}
 
Example 16
Project: RxAndroidBle   File: RxBleAdapterWrapper.java   Source Code and License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public void stopLeScan(ScanCallback scanCallback) {
    final BluetoothLeScanner bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
    if (bluetoothLeScanner == null) {
        RxBleLog.d("Cannot perform BluetoothLeScanner.stopScan(ScanCallback) because scanner is unavailable (Probably adapter is off)");
        // if stopping the scan is not possible due to BluetoothLeScanner not accessible then it is probably stopped anyway
        return;
    }
    bluetoothLeScanner.stopScan(scanCallback);
}
 
Example 17
Project: TappyBLE   File: LollipopBleScanner.java   Source Code and License 5 votes vote down vote up
@Override
@RequiresPermission(allOf = {Manifest.permission.BLUETOOTH_ADMIN,Manifest.permission.BLUETOOTH})
public void startScan(@NonNull ScanCallback callback) {
    ScannerUtils.throwOnAdaptorNotEnabled(bluetoothAdapter);
    final BluetoothLeScanner nativeScanner = getNativeScannerOrThrow();

    throwIfCallbackInUse(callback);

    ScanCallbackHolder holder = new ScanCallbackHolder(callback);
    callbackHolderMap.put(callback,holder);

    nativeScanner.startScan(holder.getNativeCallback());
}
 
Example 18
Project: TappyBLE   File: LollipopBleScanner.java   Source Code and License 5 votes vote down vote up
@Override
public void startScan(List<ScanFilter> filters, @NonNull ScanSettings settings, @NonNull ScanCallback callback) {
    ScannerUtils.throwOnAdaptorNotEnabled(bluetoothAdapter);
    final BluetoothLeScanner nativeScanner = getNativeScannerOrThrow();

    throwIfCallbackInUse(callback);

    ScanCallbackHolder holder = new ScanCallbackHolder(callback,settings,filters);
    callbackHolderMap.put(callback,holder);
    nativeScanner.startScan(holder.getNativeFilters(), holder.getNativeScanSettings(), holder.getNativeCallback());
}
 
Example 19
Project: TappyBLE   File: LollipopBleScanner.java   Source Code and License 5 votes vote down vote up
@Override
public void flushPendingScanResults(@NonNull ScanCallback callback) {
    ScannerUtils.throwOnAdaptorNotEnabled(bluetoothAdapter);
    BluetoothLeScanner nativeScanner = getNativeScannerOrThrow();

    ScanCallbackHolder holder = callbackHolderMap.get(callback);
    if(holder == null)
        throw new IllegalArgumentException("Callback not registered");

    nativeScanner.flushPendingScanResults(holder.getNativeCallback());
}
 
Example 20
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 21
Project: ibeacon-scanner-android   File: DefaultBluetoothFactory.java   Source Code and License 5 votes vote down vote up
/**
 * @return the {@link BluetoothLeScanner}
 */
@Override
@Nullable
public BluetoothLeScanner getBluetoothLeScanner()
{
    return this.canAttachBluetoothAdapter() ? this.bluetoothAdapter.getBluetoothLeScanner() : null;
}
 
Example 22
Project: android-buruberi   File: ShadowBluetoothAdapterExt.java   Source Code and License 5 votes vote down vote up
@Implementation
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public BluetoothLeScanner getBluetoothLeScanner() {
    if (bluetoothLeScanner == null) {
        this.bluetoothLeScanner = ReflectionHelpers.newInstance(BluetoothLeScanner.class);
    }

    return bluetoothLeScanner;
}
 
Example 23
Project: 365browser   File: Wrappers.java   Source Code and License 5 votes vote down vote up
public BluetoothLeScannerWrapper getBluetoothLeScanner() {
    BluetoothLeScanner scanner = mAdapter.getBluetoothLeScanner();
    if (scanner == null) {
        return null;
    }
    if (mScannerWrapper == null) {
        mScannerWrapper = new BluetoothLeScannerWrapper(scanner);
    }
    return mScannerWrapper;
}
 
Example 24
Project: SweetBlue   File: L_Util.java   Source Code and License 5 votes vote down vote up
public static void stopNativeScan(BluetoothAdapter adapter) {
    if (adapter == null)
    {
        Log.e("ScanManager", "Tried to stop the scan, but the Bluetooth Adapter instance was null!");
        return;
    }

    final BluetoothLeScanner scanner = adapter.getBluetoothLeScanner();
    if (scanner != null)
        scanner.stopScan(m_callback);
    else
        Log.w("ScanManager", "Tried to stop the scan, but the BluetoothLeScanner instance was null. This implies the scanning has stopped already.");
}
 
Example 25
Project: android-beacon-library   File: StartupBroadcastReceiver.java   Source Code and License 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    LogManager.d(TAG, "onReceive called in startup broadcast receiver");
    if (android.os.Build.VERSION.SDK_INT < 18) {
        LogManager.w(TAG, "Not starting up beacon service because we do not have API version 18 (Android 4.3).  We have: %s", android.os.Build.VERSION.SDK_INT);
        return;
    }
    BeaconManager beaconManager = BeaconManager.getInstanceForApplication(context.getApplicationContext());
    if (beaconManager.isAnyConsumerBound() || beaconManager.getScheduledScanJobsEnabled()) {
        int bleCallbackType = intent.getIntExtra(BluetoothLeScanner.EXTRA_CALLBACK_TYPE, -1); // e.g. ScanSettings.CALLBACK_TYPE_FIRST_MATCH
        if (bleCallbackType != -1) {
            LogManager.d(TAG, "Passive background scan callback type: "+bleCallbackType);
            LogManager.d(TAG, "got Android O background scan via intent");
            int errorCode = intent.getIntExtra(BluetoothLeScanner.EXTRA_ERROR_CODE, -1); // e.g.  ScanCallback.SCAN_FAILED_INTERNAL_ERROR
            if (errorCode != -1) {
                LogManager.w(TAG, "Passive background scan failed.  Code; "+errorCode);
            }
            ArrayList<ScanResult> scanResults = intent.getParcelableArrayListExtra(BluetoothLeScanner.EXTRA_LIST_SCAN_RESULT);
            ScanJobScheduler.getInstance().scheduleAfterBackgroundWakeup(context, scanResults);
        }
        else if (intent.getBooleanExtra("wakeup", false)) {
            LogManager.d(TAG, "got wake up intent");
        }
        else {
            LogManager.d(TAG, "Already started.  Ignoring intent: %s of type: %s", intent,
                    intent.getStringExtra("wakeup"));
        }
    }
    else {
        LogManager.d(TAG, "No consumers are bound.  Ignoring broadcast receiver.");
    }
 }
 
Example 26
Project: libble-android   File: BleService.java   Source Code and License 5 votes vote down vote up
/**
 * Stops an ongoing BLE Scan for the given callback.
 *
 * @param callback An instance of the BleScanCallback, used to start the scan.
 */
public void stopScan(@NonNull final BleScanCallback callback) {
    if (mBluetoothAdapter == null) {
        Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
        return;
    }

    if (mStopScanningRunnable == null) return;

    mScanHandler.removeCallbacks(mStopScanningRunnable);
    final BluetoothLeScanner bluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
    bluetoothLeScanner.stopScan(callback);
    mStopScanningRunnable = null;
    callback.onScanStopped();
}
 
Example 27
Project: TappyBLE   File: LollipopBleScanner.java   Source Code and License 4 votes vote down vote up
protected BluetoothLeScanner getNativeScannerOrThrow() {
    BluetoothLeScanner scanner = bluetoothAdapter.getBluetoothLeScanner();
    if(scanner == null)
        throw new IllegalStateException("Could not get scanner");
    return scanner;
}
 
Example 28
Project: BLECommunication   File: BLEUtil.java   Source Code and License 4 votes vote down vote up
public void scanPeripheralWithServicesUUID_API21(final String uuid) {
    	if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
    		requestOpenBT();
    		return;
    	}
    	BluetoothLeScanner scanner = mBluetoothAdapter.getBluetoothLeScanner();
    	ScanSettings settings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();
    	List<ScanFilter> list = new ArrayList<ScanFilter>(1);
    	
    	ScanCallback callback = new ScanCallback() {
			@Override
		    public void onScanResult(int callbackType,  android.bluetooth.le.ScanResult result) {
				BluetoothDevice device = result.getDevice();
				
				ScanRecord sr = result.getScanRecord();
			    
				int rssi = result.getRssi();
//				if (rssi > -15) {
//					runCallbackWithErrorCode(BLEUtilErrorCode.E_RSSI_ERROR);
//					return;
//				}
//				if (rssi < -35) {
//					runCallbackWithErrorCode(BLEUtilErrorCode.E_RSSI_TOO_LOW);
//					return;
//				}
				if (matchRules(rssi, sr.getBytes(), uuid)) {
					connectToDevice(device);
				}
		    }
		 
		    @Override
		    public void onScanFailed(int errorCode) {
		 
		    }
		};
    	
    	if (uuid != null) {
	    	ScanFilter filter = new ScanFilter.Builder().setServiceUuid(ParcelUuid.fromString(uuid)).build();
	        list.add(filter);
	        scanner.startScan(list, settings, callback);
    	} else {
//    		scanner.startScan(null, settings, callback);
    		scanner.startScan(callback);
    	}
    }
 
Example 29
Project: BLECommunication   File: BLEUtil.java   Source Code and License 4 votes vote down vote up
public void scanPeripheralWithServicesUUID_API21(final String uuid) {
    	if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
    		requestOpenBT();
    		return;
    	}
    	BluetoothLeScanner scanner = mBluetoothAdapter.getBluetoothLeScanner();
    	ScanSettings settings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();
    	List<ScanFilter> list = new ArrayList<ScanFilter>(1);
    	
    	ScanCallback callback = new ScanCallback() {
			@Override
		    public void onScanResult(int callbackType,  android.bluetooth.le.ScanResult result) {
				BluetoothDevice device = result.getDevice();
				
				ScanRecord sr = result.getScanRecord();
			    
				int rssi = result.getRssi();
//				if (rssi > -15) {
//					runCallbackWithErrorCode(BLEUtilErrorCode.E_RSSI_ERROR);
//					return;
//				}
//				if (rssi < -35) {
//					runCallbackWithErrorCode(BLEUtilErrorCode.E_RSSI_TOO_LOW);
//					return;
//				}
				if (matchRules(rssi, sr.getBytes(), uuid)) {
					connectToDevice(device);
				}
		    }
		 
		    @Override
		    public void onScanFailed(int errorCode) {
		 
		    }
		};
    	
    	if (uuid != null) {
	    	ScanFilter filter = new ScanFilter.Builder().setServiceUuid(ParcelUuid.fromString(uuid)).build();
	        list.add(filter);
	        scanner.startScan(list, settings, callback);
    	} else {
//    		scanner.startScan(null, settings, callback);
    		scanner.startScan(callback);
    	}
    }
 
Example 30
Project: android-buruberi   File: BuruberiShadows.java   Source Code and License 4 votes vote down vote up
public static ShadowBluetoothLeScanner shadowOf(@NonNull BluetoothLeScanner bluetoothAdapter) {
    return (ShadowBluetoothLeScanner) ShadowExtractor.extract(bluetoothAdapter);
}
 
Example 31
Project: 365browser   File: Wrappers.java   Source Code and License 4 votes vote down vote up
public BluetoothLeScannerWrapper(BluetoothLeScanner scanner) {
    mScanner = scanner;
    mCallbacks = new HashMap<ScanCallbackWrapper, ForwardScanCallbackToWrapper>();
}
 
Example 32
Project: android-ble   File: BleScannerL.java   Source Code and License 4 votes vote down vote up
private BluetoothLeScanner getScanner() {
    if (scanner == null && bluetoothAdapter != null) {
        scanner = bluetoothAdapter.getBluetoothLeScanner();
    }
    return scanner;
}
 
Example 33
Project: libble-android   File: BleService.java   Source Code and License 4 votes vote down vote up
/**
 * Starts a BLE Scan. Discovered devices are reported via the delivered callback.
 *
 * @param callback                    An instance of the BleScanCallback, used to receive scan results.
 * @param durationMs                  The duration in milliseconds, how long the scan should last. This parameter
 *                                    must be greater or equal to 1000 ms.
 * @param deviceNameFilter            A array of device names to filter for. Only BLE devices with these
 *                                    names are reported to the callback.
 * @param advertisedServiceUuidFilter An Array of advertised service UUIDs to also deliver results for.
 * @return true if a scan was triggered and false, if it was not possible to trigger a scan or
 * if there is already an ongoing scan running.
 */
public boolean startScan(@NonNull final BleScanCallback callback, final long durationMs,
                         final String[] deviceNameFilter, final String[] advertisedServiceUuidFilter) {
    if (mBluetoothAdapter == null) {
        Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
        return false;
    }

    if (durationMs < MIN_SCAN_DURATION_MS) {
        Log.w(TAG, "The scan duration must be longer than 1 second");
        return false;
    }

    if (mStopScanningRunnable != null) {
        Log.w(TAG, "Already a scan running");
        return false;
    }

    final BluetoothLeScanner bluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
    if (bluetoothLeScanner == null) {
        Log.w(TAG, "Failed to scan. Bluetooth appears to be unavailable");
        return false;
    }
    final ScanSettings settings = new ScanSettings.Builder()
            .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
            .build();

    final List<ScanFilter> filters = getScanFilters(deviceNameFilter, advertisedServiceUuidFilter);

    // Stops scanning after a pre-defined scan period.
    mStopScanningRunnable = new Runnable() {
        @Override
        public void run() {
            stopScan(callback);
        }
    };
    mScanHandler.postDelayed(mStopScanningRunnable, durationMs);

    bluetoothLeScanner.startScan(filters, settings, callback);
    return true;
}
 
Example 34
Project: ibeacon-scanner-android   File: BluetoothFactory.java   Source Code and License 2 votes vote down vote up
/**
 * @return a {@link BluetoothLeScanner}
 */
@Nullable
BluetoothLeScanner getBluetoothLeScanner();