Java Code Examples for android.bluetooth.BluetoothAdapter#getBluetoothLeScanner()

The following examples show how to use android.bluetooth.BluetoothAdapter#getBluetoothLeScanner() . 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 File: LollipopScanner.java    From RxCentralBle with 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 2
Source File: BluetoothLeScannerImplOreo.java    From Android-Scanner-Compat-Library with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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 3
Source File: SerialInterface_BLE.java    From PodEmu with 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 4
Source File: BluetoothLeScannerImplLollipop.java    From Android-Scanner-Compat-Library with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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 5
Source File: BluetoothLeScannerImplLollipop.java    From Android-Scanner-Compat-Library with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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 6
Source File: DalvikBleService.java    From attach with GNU General Public License v3.0 6 votes vote down vote up
private void init() {
    Log.v(TAG, "DalvikBle, init");
    boolean fineloc = Util.verifyPermissions(Manifest.permission.ACCESS_FINE_LOCATION);
    if (!fineloc) {
        Log.v(TAG, "No permission to get fine location");
    }
    final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    if (!adapter.isEnabled()) {
        Log.v(TAG, "DalvikBle, init, adapter not enabled");
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        IntentHandler intentHandler = new IntentHandler() {
            @Override
            public void gotActivityResult (int requestCode, int resultCode, Intent intent) {
                if (requestCode == REQUEST_ENABLE_BT && resultCode == RESULT_OK) {
                    scanner = adapter.getBluetoothLeScanner();
                }
            }
        };

        if (activity == null) {
            LOG.log(Level.WARNING, "Activity not found. This service is not allowed when "
                    + "running in background mode or from wearable");
            return;
        }
        Util.setOnActivityResultHandler(intentHandler);

        // A dialog will appear requesting user permission to enable Bluetooth
        activity.startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);

    } else {
        scanner = adapter.getBluetoothLeScanner();
    }

}
 
Example 7
Source File: BLEScanner.java    From DeviceConnect-Android with MIT License 6 votes vote down vote up
public void startScan(final Context context) {
    if (DEBUG) {
        Log.d(TAG, "startScan()");
        Log.d(TAG, "context : " + context);
    }
    synchronized (mLock) {
        BluetoothManager bluetoothManager = ((BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE));
        if (bluetoothManager != null) {
            BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
            mBluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
            if (!mIsScanning) {
                mIsScanning = true;
                mBluetoothLeScanner.startScan(mScanFilters, mScanSettings, mScanCallback);
                new Handler(Looper.getMainLooper()).postDelayed(this::stopScan, SCAN_PERIOD_MILLISECONDS);
            }
        }
    }
}
 
Example 8
Source File: BLEScanActivity.java    From AndroidAPS with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
protected void onResume() {
    super.onResume();

    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBluetoothAdapter != null) {
        if (!mBluetoothAdapter.isEnabled()) mBluetoothAdapter.enable();
        mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();

        if (mBluetoothLeScanner == null) {
            mBluetoothAdapter.enable();
            mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
        }
        startScan();
    }
}
 
Example 9
Source File: ThrottledLollipopScanner.java    From RxCentralBle with 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 10
Source File: LollipopScanner.java    From RxCentralBle with 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 11
Source File: L_Util.java    From AsteroidOSSync with GNU General Public License v3.0 5 votes vote down vote up
static void startScan(BluetoothAdapter adapter, ScanSettings scanSettings, ScanCallback listener) {
    m_UserScanCallback = listener;
    // Add a last ditch check to make sure the adapter isn't null before trying to start the scan.
    // We check in the task, but by the time we reach this method, it could have been shut off
    // Either the adapter, or the scanner object may be null, so we check it here
    if (adapter == null || adapter.getBluetoothLeScanner() == null)
    {
        m_callback.onScanFailed(android.bluetooth.le.ScanCallback.SCAN_FAILED_INTERNAL_ERROR);
        return;
    }
    adapter.getBluetoothLeScanner().startScan(null, scanSettings, m_callback);
}
 
Example 12
Source File: BluetoothLeScannerImplOreo.java    From Android-Scanner-Compat-Library with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@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 13
Source File: L_Util.java    From AsteroidOSSync with 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 14
Source File: BluetoothLeScannerImplLollipop.java    From Android-Scanner-Compat-Library with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@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 15
Source File: ThrottledLollipopScanner.java    From RxCentralBle with 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 16
Source File: BluetoothLeScannerImplLollipop.java    From Android-Scanner-Compat-Library with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@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 17
Source File: SerialInterface_BLE.java    From PodEmu with 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 18
Source File: L_Util.java    From SweetBlue with 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 19
Source File: L_Util.java    From SweetBlue with GNU General Public License v3.0 5 votes vote down vote up
static void startScan(BluetoothAdapter adapter, ScanSettings scanSettings, ScanCallback listener) {
    m_UserScanCallback = listener;
    // Add a last ditch check to make sure the adapter isn't null before trying to start the scan.
    // We check in the task, but by the time we reach this method, it could have been shut off
    // Either the adapter, or the scanner object may be null, so we check it here
    if (adapter == null || adapter.getBluetoothLeScanner() == null)
    {
        m_callback.onScanFailed(android.bluetooth.le.ScanCallback.SCAN_FAILED_INTERNAL_ERROR);
        return;
    }
    adapter.getBluetoothLeScanner().startScan(getFilterList(), scanSettings, m_callback);
}
 
Example 20
Source File: SerialInterface_BLE.java    From PodEmu with 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();
    }