Java Code Examples for android.bluetooth.le.BluetoothLeScanner

The following examples show how to use android.bluetooth.le.BluetoothLeScanner. 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   Source File: BluetoothAdapter.java    License: Apache License 2.0 7 votes vote down vote up
/**
 * 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: RxCentralBle   Source 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: RxCentralBle   Source File: LollipopScanner.java    License: Apache License 2.0 6 votes vote down vote up
private void stopScan() {
  BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
  if (adapter != null && adapter.isEnabled()) {
    BluetoothLeScanner bleScanner = adapter.getBluetoothLeScanner();
    if (bleScanner != null) {
      bleScanner.stopScan(scanCallback);
    } else if (RxCentralLogger.isError()) {
      RxCentralLogger.error("stopScan - BluetoothLeScanner is null!");
    }
  } else if (RxCentralLogger.isError()) {
    if (adapter == null) {
      RxCentralLogger.error("stopScan - Default Bluetooth Adapter is null!");
    } else {
      RxCentralLogger.error("stopScan - Bluetooth Adapter is disabled.");
    }
  }

  scanDataSubject = null;
}
 
Example 4
Source Project: RxCentralBle   Source File: ThrottledLollipopScanner.java    License: Apache License 2.0 6 votes vote down vote up
private void stopScan() {
  BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
  if (adapter != null && adapter.isEnabled()) {
    BluetoothLeScanner bleScanner = adapter.getBluetoothLeScanner();
    if (bleScanner != null) {
      bleScanner.stopScan(scanCallback);
    } else if (RxCentralLogger.isError()) {
      RxCentralLogger.error("stopScan - BluetoothLeScanner is null!");
    }
  } else if (RxCentralLogger.isError()) {
    if (adapter == null) {
      RxCentralLogger.error("stopScan - Default Bluetooth Adapter is null!");
    } else {
      RxCentralLogger.error("stopScan - Bluetooth Adapter is disabled.");
    }
  }
}
 
Example 5
Source Project: RxAndroidBle   Source File: BackgroundScannerImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public List<ScanResult> onScanResultReceived(@NonNull Intent intent) {
    final int callbackType = intent.getIntExtra(BluetoothLeScanner.EXTRA_CALLBACK_TYPE, -1);
    final int errorCode = intent.getIntExtra(BluetoothLeScanner.EXTRA_ERROR_CODE, NO_ERROR);
    final List<android.bluetooth.le.ScanResult> nativeScanResults = extractScanResults(intent);
    ArrayList<ScanResult> scanResults = new ArrayList<>();

    if (errorCode == NO_ERROR) {
        for (android.bluetooth.le.ScanResult result : nativeScanResults) {
            scanResults.add(convertScanResultToRxAndroidBLEModel(callbackType, result));
        }

        return scanResults;
    } else {
        throw new BleScanException(errorCode);
    }
}
 
Example 6
Source Project: RxAndroidBle   Source File: RxBleAdapterWrapper.java    License: Apache License 2.0 6 votes vote down vote up
@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 7
@RequiresPermission(Manifest.permission.BLUETOOTH_ADMIN)
/* package */ void stopScanInternal(@NonNull final Context context,
									@NonNull final PendingIntent callbackIntent) {
	final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
	final BluetoothLeScanner scanner = adapter.getBluetoothLeScanner();
	if (scanner == null)
		throw new IllegalStateException("BT le scanner not available");

	final PendingIntent pendingIntent = createStoppingPendingIntent(context, callbackIntent);
	scanner.stopScan(pendingIntent);

	synchronized (wrappers) {
		// Do not remove the key, just set the value to null.
		// Based on that we will know that scanning has been stopped.
		// This is used to discard scanning results delivered after the scan was stopped.
		// Unfortunately, the callbackIntent will have to be kept and won't he removed,
		// despite the fact that reports will eventually stop being broadcast.
		wrappers.put(callbackIntent, null);
	}
}
 
Example 8
@Override
@RequiresPermission(allOf = {Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.BLUETOOTH})
/* package */ void stopScanInternal(@NonNull final ScanCallback callback) {
	ScanCallbackWrapperLollipop wrapper;
	synchronized (wrappers) {
		wrapper = wrappers.remove(callback);
	}
	if (wrapper == null)
		return;

	wrapper.close();

	final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
	if (adapter != null) {
		final BluetoothLeScanner scanner = adapter.getBluetoothLeScanner();
		if (scanner != null)
			scanner.stopScan(wrapper.nativeCallback);
	}
}
 
Example 9
@Override
@RequiresPermission(allOf = {Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.BLUETOOTH})
	/* package */ void startScanInternal(@NonNull final List<ScanFilter> filters,
										 @NonNull final ScanSettings settings,
										 @NonNull final Context context,
										 @NonNull final PendingIntent callbackIntent) {
	final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
	final BluetoothLeScanner scanner = adapter.getBluetoothLeScanner();
	if (scanner == null)
		throw new IllegalStateException("BT le scanner not available");

	final Intent service = new Intent(context, ScannerService.class);
	service.putParcelableArrayListExtra(ScannerService.EXTRA_FILTERS, new ArrayList<>(filters));
	service.putExtra(ScannerService.EXTRA_SETTINGS, settings);
	service.putExtra(ScannerService.EXTRA_PENDING_INTENT, callbackIntent);
	service.putExtra(ScannerService.EXTRA_START, true);
	context.startService(service);
}
 
Example 10
Source Project: PodEmu   Source File: SerialInterface_BLE.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onScanResult(int callbackType, ScanResult result)
{
    //String bleDeviceAddress = getSharedPref().getString("bluetoothDeviceAddress", "unknown");
    //String devName = device.getName() + " [" + device.getAddress() + "]";
    //PodEmuLog.debug("SIBLE: device found - " + devName);

    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    BluetoothLeScanner bluetoothLeScanner = adapter.getBluetoothLeScanner();
    //Do the work below on a worker thread instead!
    bleDevice = result.getDevice();

    bluetoothLeScanner.stopScan(this);
    setState(STATE_CONNECTING);

    bleGATT = bleDevice.connectGatt(baseContext, false, bleGattCallback);
    bleGATT.requestConnectionPriority(BluetoothGatt.CONNECTION_PRIORITY_HIGH);

}
 
Example 11
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 12
Source Project: easyble-x   Source File: LeScanner.java    License: Apache License 2.0 5 votes vote down vote up
private BluetoothLeScanner getLeScanner() {
    if (bleScanner == null) {
        //如果蓝牙未开启的时候,获取到是null
        bleScanner = bluetoothAdapter.getBluetoothLeScanner();
    }
    return bleScanner;
}
 
Example 13
Source Project: RxCentralBle   Source File: ThrottledLollipopScanner.java    License: Apache License 2.0 5 votes vote down vote up
private void startScan(int scanMode) {
  BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
  if (adapter != null && adapter.isEnabled()) {
    // Add a dummy filter to avoid Android 8.1+ enforcement of filters during background isScanning.
    List<ScanFilter> filters = new ArrayList<>();
    ScanFilter.Builder scanFilterBuilder = new ScanFilter.Builder();
    filters.add(scanFilterBuilder.build());

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

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

      getErrorSubject().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.");
      }
    }

    getErrorSubject().onError(new ConnectionError(SCAN_FAILED));
  }
}
 
Example 14
Source Project: AsteroidOSSync   Source File: L_Util.java    License: GNU General Public License v3.0 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 15
@Override
@RequiresPermission(allOf = {Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.BLUETOOTH})
/* package */ void startScanInternal(@Nullable final List<ScanFilter> filters,
									 @Nullable final ScanSettings settings,
									 @NonNull  final Context context,
									 @NonNull  final PendingIntent callbackIntent) {
	final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
	final BluetoothLeScanner scanner = adapter.getBluetoothLeScanner();
	if (scanner == null)
		throw new IllegalStateException("BT le scanner not available");

	final ScanSettings nonNullSettings = settings != null ? settings : new ScanSettings.Builder().build();
	final List<ScanFilter> nonNullFilters = filters != null ? filters : Collections.<ScanFilter>emptyList();

	final android.bluetooth.le.ScanSettings nativeSettings = toNativeScanSettings(adapter, nonNullSettings, false);
	List<android.bluetooth.le.ScanFilter> nativeFilters = null;
	if (filters != null && adapter.isOffloadedFilteringSupported() && nonNullSettings.getUseHardwareFilteringIfSupported())
		nativeFilters = toNativeScanFilters(filters);

	synchronized (wrappers) {
		// Make sure there is not such callbackIntent in the map.
		// The value could have been set to null when the same intent was used before.
		wrappers.remove(callbackIntent);
	}

	final PendingIntent pendingIntent = createStartingPendingIntent(nonNullFilters,
			nonNullSettings, context, callbackIntent);
	scanner.startScan(nativeFilters, nativeSettings, pendingIntent);
}
 
Example 16
@Override
@RequiresPermission(allOf = {Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.BLUETOOTH})
/* package */ void startScanInternal(@NonNull final List<ScanFilter> filters,
									 @NonNull final ScanSettings settings,
									 @NonNull final ScanCallback callback,
									 @NonNull final Handler handler) {
	final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
	final BluetoothLeScanner scanner = adapter.getBluetoothLeScanner();
	if (scanner == null)
		throw new IllegalStateException("BT le scanner not available");

	final boolean offloadedBatchingSupported = adapter.isOffloadedScanBatchingSupported();
	final boolean offloadedFilteringSupported = adapter.isOffloadedFilteringSupported();

	ScanCallbackWrapperLollipop wrapper;

	synchronized (wrappers) {
		if (wrappers.containsKey(callback)) {
			throw new IllegalArgumentException("scanner already started with given callback");
		}
		wrapper = new ScanCallbackWrapperLollipop(offloadedBatchingSupported,
				offloadedFilteringSupported, filters, settings, callback, handler);
		wrappers.put(callback, wrapper);
	}

	final android.bluetooth.le.ScanSettings nativeScanSettings = toNativeScanSettings(adapter, settings, false);
	List<android.bluetooth.le.ScanFilter> nativeScanFilters = null;
	if (!filters.isEmpty() && offloadedFilteringSupported && settings.getUseHardwareFilteringIfSupported())
		nativeScanFilters = toNativeScanFilters(filters);

	scanner.startScan(nativeScanFilters, nativeScanSettings, wrapper.nativeCallback);
}
 
Example 17
@Override
@RequiresPermission(Manifest.permission.BLUETOOTH)
public void flushPendingScanResults(@NonNull final ScanCallback callback) {
	final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
	//noinspection ConstantConditions
	if (callback == null) {
		throw new IllegalArgumentException("callback cannot be null!");
	}

	ScanCallbackWrapperLollipop wrapper;
	synchronized (wrappers) {
		wrapper = wrappers.get(callback);
	}

	if (wrapper == null) {
		throw new IllegalArgumentException("callback not registered!");
	}

	final ScanSettings settings = wrapper.scanSettings;
	if (adapter.isOffloadedScanBatchingSupported() && settings.getUseHardwareBatchingIfSupported()) {
		final BluetoothLeScanner scanner = adapter.getBluetoothLeScanner();
		if (scanner == null)
			return;
		scanner.flushPendingScanResults(wrapper.nativeCallback);
	} else {
		wrapper.flushPendingScanResults();
	}
}
 
Example 18
Source Project: 365browser   Source File: Wrappers.java    License: Apache License 2.0 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 19
Source Project: PodEmu   Source File: SerialInterface_BLE.java    License: GNU General Public License v3.0 5 votes vote down vote up
@TargetApi(21)
public void close()
{
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    BluetoothLeScanner bluetoothLeScanner = adapter.getBluetoothLeScanner();
    bluetoothLeScanner.stopScan(new MyScanCallback());

    if(bleGATT!=null) bleGATT.close();
    bleGATT=null;
    bleDevice=null;
    bleScanThread=null;
    mInBuffer.removeAll();
    releaseWriteLock();
}
 
Example 20
Source Project: SweetBlue   Source File: L_Util.java    License: GNU General Public License v3.0 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 21
@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 22
Source Project: blessed-android   Source File: ShadowBluetoothLEAdapter.java    License: MIT License 4 votes vote down vote up
public void setBluetoothLeScanner(BluetoothLeScanner scanner) {
    this.scanner = scanner;
}
 
Example 23
Source Project: blessed-android   Source File: ShadowBluetoothLEAdapter.java    License: MIT License 4 votes vote down vote up
@Implementation(minSdk = LOLLIPOP)
public BluetoothLeScanner getBluetoothLeScanner() {
    return scanner;
}
 
Example 24
Source Project: RxAndroidBle   Source File: BackgroundScannerImpl.java    License: Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private static List<android.bluetooth.le.ScanResult> extractScanResults(@NonNull Intent intent) {
    return (List<android.bluetooth.le.ScanResult>) intent.getSerializableExtra(BluetoothLeScanner.EXTRA_LIST_SCAN_RESULT);
}
 
Example 25
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onReceive(final Context context, final Intent intent) {
	// Ensure we are ok.
	if (context == null || intent == null)
		return;

	// Find the target pending intent.
	final PendingIntent callbackIntent = intent.getParcelableExtra(EXTRA_PENDING_INTENT);
	if (callbackIntent == null)
		return;

	// Filters and settings have been set as native objects, otherwise they could not be
	// serialized by the system scanner.
	final ArrayList<android.bluetooth.le.ScanFilter> nativeScanFilters =
			intent.getParcelableArrayListExtra(EXTRA_FILTERS);
	final android.bluetooth.le.ScanSettings nativeScanSettings = intent.getParcelableExtra(EXTRA_SETTINGS);
	if (nativeScanFilters == null || nativeScanSettings == null)
		return;

	// Some ScanSettings parameters are only on compat version and need to be sent separately.
	final boolean useHardwareBatchingIfSupported = intent.getBooleanExtra(EXTRA_USE_HARDWARE_BATCHING, true);
	final boolean useHardwareFilteringIfSupported = intent.getBooleanExtra(EXTRA_USE_HARDWARE_FILTERING, true);
	final boolean useHardwareCallbackTypesIfSupported = intent.getBooleanExtra(EXTRA_USE_HARDWARE_CALLBACK_TYPES, true);
	final long matchLostDeviceTimeout = intent.getLongExtra(EXTRA_MATCH_LOST_TIMEOUT, ScanSettings.MATCH_LOST_DEVICE_TIMEOUT_DEFAULT);
	final long matchLostTaskInterval = intent.getLongExtra(EXTRA_MATCH_LOST_INTERVAL, ScanSettings.MATCH_LOST_TASK_INTERVAL_DEFAULT);
	final int matchMode = intent.getIntExtra(EXTRA_MATCH_MODE, ScanSettings.MATCH_MODE_AGGRESSIVE);
	final int numOfMatches = intent.getIntExtra(EXTRA_NUM_OF_MATCHES, ScanSettings.MATCH_NUM_MAX_ADVERTISEMENT);

	// Convert native objects to compat versions.
	final BluetoothLeScannerCompat scanner = BluetoothLeScannerCompat.getScanner();
	final BluetoothLeScannerImplOreo scannerImpl = (BluetoothLeScannerImplOreo) scanner;
	final ArrayList<ScanFilter> filters = scannerImpl.fromNativeScanFilters(nativeScanFilters);
	final ScanSettings settings = scannerImpl.fromNativeScanSettings(nativeScanSettings,
			useHardwareBatchingIfSupported,
			useHardwareFilteringIfSupported,
			useHardwareCallbackTypesIfSupported,
			matchLostDeviceTimeout, matchLostTaskInterval,
			matchMode, numOfMatches);

	// Check device capabilities and create a wrapper that will send a PendingIntent.
	final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
	final boolean offloadedBatchingSupported = adapter.isOffloadedScanBatchingSupported();
	final boolean offloadedFilteringSupported = adapter.isOffloadedFilteringSupported();

	// Obtain or create a PendingIntentExecutorWrapper. A static instance (obtained from a
	// static BluetoothLeScannerCompat singleton) is necessary as it allows to keeps
	// track of found devices and emulate batching and callback types if those are not
	// supported or a compat version was forced.

	BluetoothLeScannerImplOreo.PendingIntentExecutorWrapper wrapper;
	//noinspection SynchronizationOnLocalVariableOrMethodParameter
	synchronized (scanner) {
		try {
			wrapper = scannerImpl.getWrapper(callbackIntent);
		} catch (final IllegalStateException e) {
			// Scanning has been stopped.
			return;
		}
		if (wrapper == null) {
			// Wrapper has not been created, or was created, but the app was then killed
			// and must be created again. Some information will be lost (batched devices).
			wrapper = new BluetoothLeScannerImplOreo.PendingIntentExecutorWrapper(offloadedBatchingSupported,
					offloadedFilteringSupported, filters, settings, callbackIntent);
			scannerImpl.addWrapper(callbackIntent, wrapper);
		}
	}

	// The context may change each time. Set the one time temporary context that will be used
	// to send PendingIntent. It will be released after the results were handled.
	wrapper.executor.setTemporaryContext(context);

	// Check what results were received and send them to PendingIntent.
	final List<android.bluetooth.le.ScanResult> nativeScanResults =
			intent.getParcelableArrayListExtra(BluetoothLeScanner.EXTRA_LIST_SCAN_RESULT);
	if (nativeScanResults != null) {
		final ArrayList<ScanResult> results = scannerImpl.fromNativeScanResults(nativeScanResults);

		if (settings.getReportDelayMillis() > 0) {
			wrapper.handleScanResults(results);
		} else if (!results.isEmpty()) {
			final int callbackType = intent.getIntExtra(BluetoothLeScanner.EXTRA_CALLBACK_TYPE,
					ScanSettings.CALLBACK_TYPE_ALL_MATCHES);
			wrapper.handleScanResult(callbackType, results.get(0));
		}
	} else {
		final int errorCode = intent.getIntExtra(BluetoothLeScanner.EXTRA_ERROR_CODE, 0);
		if (errorCode != 0) {
			wrapper.handleScanError(errorCode);
		}
	}

	// Release the temporary context reference, so that static executor does not hold a
	// reference to a context.
	wrapper.executor.setTemporaryContext(null);
}
 
Example 26
Source Project: 365browser   Source File: Wrappers.java    License: Apache License 2.0 4 votes vote down vote up
public BluetoothLeScannerWrapper(BluetoothLeScanner scanner) {
    mScanner = scanner;
    mCallbacks = new HashMap<ScanCallbackWrapper, ForwardScanCallbackToWrapper>();
}
 
Example 27
Source Project: PodEmu   Source File: SerialInterface_BLE.java    License: GNU General Public License v3.0 4 votes vote down vote up
@TargetApi(21)
    public synchronized boolean init(Context context)
    {
        PodEmuLog.debug("SIBLE: init()");

        if(bleScanThread!=null)
        {
            PodEmuLog.debug("SIBLE: bleScanThread already running. Skipping initialization.");
        }
        else if(bleDevice==null)
        {
            PodEmuLog.debug("SIBLE: starting new BLE scan");
            /*bleScanThread = new Thread(new Runnable()
            {
                @Override
                public void run()
                {
*/
            try
            {
                PodEmuLog.debug("SIBLE: BLE scan started.");
                ScanSettings scanSettings = new ScanSettings.Builder()
                        .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                        .build();

                ScanFilter scanFilter = new ScanFilter.Builder()
                        .setDeviceName(getName())
                        .setDeviceAddress(getAddress())
                        .build();

                BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
                BluetoothLeScanner bluetoothLeScanner = adapter.getBluetoothLeScanner();
                bluetoothLeScanner.startScan(Collections.singletonList(scanFilter), scanSettings, new MyScanCallback());

                setState(STATE_SEARCHING);
                SerialInterface_BLE.this.wait();
                PodEmuLog.debug("SIBLE: wait finished");
            }
            catch (InterruptedException e)
            {
                PodEmuLog.debug("SIBLE: BLE scan interrupted");
            }
/*                }
            });
            bleScanThread.start();
  */      }
        else if(bleGATT == null)
        {
            PodEmuLog.debug("SIBLE: getting new GATT handler");
            bleGATT = bleDevice.connectGatt(baseContext, true, bleGattCallback);
            bleGATT.requestConnectionPriority(BluetoothGatt.CONNECTION_PRIORITY_HIGH);
        }

        return isConnected();
    }