Search in sources :

Example 11 with ScanSettings

use of android.bluetooth.le.ScanSettings in project android-beacon-library by AltBeacon.

the class ScanHelper method startAndroidOBackgroundScan.

@RequiresApi(api = Build.VERSION_CODES.O)
void startAndroidOBackgroundScan(Set<BeaconParser> beaconParsers, List<Region> regions) {
    ScanSettings settings = (new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_POWER)).build();
    List<ScanFilter> filters = new ScanFilterUtils().createScanFiltersForBeaconParsers(new ArrayList<BeaconParser>(beaconParsers), regions);
    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, "Failed to start background scan on Android O: BluetoothAdapter is not enabled");
        } else {
            BluetoothLeScanner scanner = bluetoothAdapter.getBluetoothLeScanner();
            if (scanner != null) {
                int result = scanner.startScan(filters, settings, getScanCallbackIntent());
                if (result != 0) {
                    LogManager.e(TAG, "Failed to start background scan on Android O.  Code: " + result);
                } else {
                    LogManager.d(TAG, "Started passive beacon scan");
                }
            } else {
                LogManager.e(TAG, "Failed to start background scan on Android O: scanner is null");
            }
        }
    } catch (SecurityException e) {
        LogManager.e(TAG, "SecurityException making Android O background scanner");
    } catch (NullPointerException e) {
        // Needed to stop a crash caused by internal NPE thrown by Android.  See issue #636
        LogManager.e(TAG, "NullPointerException starting Android O background scanner", e);
    } catch (RuntimeException e) {
        // Needed to stop a crash caused by internal Android throw.  See issue #701
        LogManager.e(TAG, "Unexpected runtime exception starting Android O background scanner", e);
    }
}
Also used : ScanSettings(android.bluetooth.le.ScanSettings) BluetoothLeScanner(android.bluetooth.le.BluetoothLeScanner) ScanFilter(android.bluetooth.le.ScanFilter) BluetoothManager(android.bluetooth.BluetoothManager) ScanFilterUtils(org.altbeacon.beacon.service.scanner.ScanFilterUtils) BeaconParser(org.altbeacon.beacon.BeaconParser) BluetoothAdapter(android.bluetooth.BluetoothAdapter) RequiresApi(androidx.annotation.RequiresApi)

Example 12 with ScanSettings

use of android.bluetooth.le.ScanSettings in project android-beacon-library by AltBeacon.

the class CycledLeScannerForLollipop method startScan.

@Override
protected void startScan() {
    if (!isBluetoothOn()) {
        LogManager.d(TAG, "Not starting scan because bluetooth is off");
        return;
    }
    List<ScanFilter> filters = new ArrayList<ScanFilter>();
    ScanSettings settings = null;
    if (!mMainScanCycleActive) {
        LogManager.d(TAG, "starting filtered scan in SCAN_MODE_LOW_POWER");
        settings = (new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_POWER)).build();
        filters = new ScanFilterUtils().createScanFiltersForBeaconParsers(mBeaconManager.getBeaconParsers());
    } else {
        LogManager.d(TAG, "starting a scan in SCAN_MODE_LOW_LATENCY");
        settings = (new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)).build();
        // to cause scan failures on some Samsung devices with Android 5.x
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
            if (Build.MANUFACTURER.equalsIgnoreCase("samsung") && !mPowerManager.isInteractive()) {
                // On the Samsung Galaxy Note 8.1, scans are blocked with screen off when the
                // scan filter is empty (wildcard).  We do a more detailed filter on Samsung only
                // because it might block detections of AltBeacon packets with non-standard
                // manufacturer codes.  See #769 for details.
                LogManager.d(TAG, "Using a non-empty scan filter since this is Samsung 8.1+");
                filters = new ScanFilterUtils().createScanFiltersForBeaconParsers(mBeaconManager.getBeaconParsers());
            } else {
                if (Build.MANUFACTURER.equalsIgnoreCase("samsung")) {
                    LogManager.d(TAG, "Using a wildcard scan filter on Samsung because the screen is on.  We will switch to a non-empty filter if the screen goes off");
                    // if this is samsung, as soon as the screen goes off we will need to start a different scan
                    // that has scan filters
                    IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
                    mContext.getApplicationContext().registerReceiver(mSamsungScreenOffReceiver, filter);
                    LogManager.d(TAG, "registering SamsungScreenOffReceiver " + mSamsungScreenOffReceiver);
                } else {
                    LogManager.d(TAG, "Using an empty scan filter since this is 8.1+ on Non-Samsung");
                }
                // The wildcard filter matches everything.
                filters = new ScanFilterUtils().createWildcardScanFilters();
            }
        } else {
            LogManager.d(TAG, "Using no scan filter since this is pre-8.1");
        }
    }
    if (settings != null) {
        postStartLeScan(filters, settings);
    }
}
Also used : IntentFilter(android.content.IntentFilter) ScanSettings(android.bluetooth.le.ScanSettings) ScanFilter(android.bluetooth.le.ScanFilter) ArrayList(java.util.ArrayList)

Example 13 with ScanSettings

use of android.bluetooth.le.ScanSettings in project aware-client by denzilferreira.

the class Bluetooth method onStartCommand.

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);
    if (PERMISSIONS_OK) {
        if (intent != null && intent.hasExtra("action") && intent.getStringExtra("action").equalsIgnoreCase(ACTION_AWARE_ENABLE_BT)) {
            Intent enableBT = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            enableBT.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(enableBT);
        }
        if (bluetoothAdapter == null) {
            if (Aware.DEBUG)
                Log.w(TAG, "No bluetooth is detected on this device");
            stopSelf();
        } else {
            if (!bluetoothAdapter.isEnabled()) {
                notifyMissingBluetooth(getApplicationContext(), false);
            }
            DEBUG = Aware.getSetting(this, Aware_Preferences.DEBUG_FLAG).equals("true");
            Aware.setSetting(this, Aware_Preferences.STATUS_BLUETOOTH, true);
            if (Aware.getSetting(this, Aware_Preferences.FREQUENCY_BLUETOOTH).length() == 0) {
                Aware.setSetting(this, Aware_Preferences.FREQUENCY_BLUETOOTH, 60);
            }
            save_bluetooth_device(bluetoothAdapter);
            if (FREQUENCY != Integer.parseInt(Aware.getSetting(getApplicationContext(), Aware_Preferences.FREQUENCY_BLUETOOTH))) {
                alarmManager.cancel(bluetoothScan);
                alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + Integer.parseInt(Aware.getSetting(getApplicationContext(), Aware_Preferences.FREQUENCY_BLUETOOTH)) * 1000, Integer.parseInt(Aware.getSetting(getApplicationContext(), Aware_Preferences.FREQUENCY_BLUETOOTH)) * 2 * 1000, bluetoothScan);
                FREQUENCY = Integer.parseInt(Aware.getSetting(getApplicationContext(), Aware_Preferences.FREQUENCY_BLUETOOTH));
            }
            if (Aware.DEBUG)
                Log.d(TAG, "Bluetooth service active: " + FREQUENCY + "s");
            if (BLE_SUPPORT) {
                if (mBLEHandler == null)
                    mBLEHandler = new Handler();
                if (scanSettings == null) {
                    scanSettings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_POWER).build();
                }
            }
        }
        if (Aware.isStudy(this)) {
            ContentResolver.setIsSyncable(Aware.getAWAREAccount(this), Bluetooth_Provider.getAuthority(this), 1);
            ContentResolver.setSyncAutomatically(Aware.getAWAREAccount(this), Bluetooth_Provider.getAuthority(this), true);
            long frequency = Long.parseLong(Aware.getSetting(this, Aware_Preferences.FREQUENCY_WEBSERVICE)) * 60;
            SyncRequest request = new SyncRequest.Builder().syncPeriodic(frequency, frequency / 3).setSyncAdapter(Aware.getAWAREAccount(this), Bluetooth_Provider.getAuthority(this)).setExtras(new Bundle()).build();
            ContentResolver.requestSync(request);
        }
    }
    return START_STICKY;
}
Also used : ScanSettings(android.bluetooth.le.ScanSettings) Bundle(android.os.Bundle) Handler(android.os.Handler) PendingIntent(android.app.PendingIntent)

Example 14 with ScanSettings

use of android.bluetooth.le.ScanSettings in project platform_frameworks_base by android.

the class KeyboardUI method startScanning.

private void startScanning() {
    BluetoothLeScanner scanner = mLocalBluetoothAdapter.getBluetoothLeScanner();
    ScanFilter filter = (new ScanFilter.Builder()).setDeviceName(mKeyboardName).build();
    ScanSettings settings = (new ScanSettings.Builder()).setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES).setNumOfMatches(ScanSettings.MATCH_NUM_ONE_ADVERTISEMENT).setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).setReportDelay(0).build();
    mScanCallback = new KeyboardScanCallback();
    scanner.startScan(Arrays.asList(filter), settings, mScanCallback);
    Message abortMsg = mHandler.obtainMessage(MSG_BLE_ABORT_SCAN, ++mScanAttempt, 0);
    mHandler.sendMessageDelayed(abortMsg, BLUETOOTH_SCAN_TIMEOUT_MILLIS);
}
Also used : BluetoothLeScanner(android.bluetooth.le.BluetoothLeScanner) ScanSettings(android.bluetooth.le.ScanSettings) Message(android.os.Message) ScanFilter(android.bluetooth.le.ScanFilter)

Example 15 with ScanSettings

use of android.bluetooth.le.ScanSettings in project platform_frameworks_base by android.

the class BluetoothAdapter method startLeScan.

/**
     * Starts a scan for Bluetooth LE devices, looking for devices that
     * advertise given services.
     *
     * <p>Devices which advertise all specified services are reported using the
     * {@link LeScanCallback#onLeScan} callback.
     *
     * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN} permission.
     *
     * @param serviceUuids Array of services to look for
     * @param callback the callback LE scan results are delivered
     * @return true, if the scan was started successfully
     * @deprecated use {@link BluetoothLeScanner#startScan(List, ScanSettings, ScanCallback)}
     *             instead.
     */
@Deprecated
@RequiresPermission(Manifest.permission.BLUETOOTH_ADMIN)
public boolean startLeScan(final UUID[] serviceUuids, final LeScanCallback callback) {
    if (DBG)
        Log.d(TAG, "startLeScan(): " + Arrays.toString(serviceUuids));
    if (callback == null) {
        if (DBG)
            Log.e(TAG, "startLeScan: null callback");
        return false;
    }
    BluetoothLeScanner scanner = getBluetoothLeScanner();
    if (scanner == null) {
        if (DBG)
            Log.e(TAG, "startLeScan: cannot get BluetoothLeScanner");
        return false;
    }
    synchronized (mLeScanClients) {
        if (mLeScanClients.containsKey(callback)) {
            if (DBG)
                Log.e(TAG, "LE Scan has already started");
            return false;
        }
        try {
            IBluetoothGatt iGatt = mManagerService.getBluetoothGatt();
            if (iGatt == null) {
                // BLE is not supported
                return false;
            }
            ScanCallback scanCallback = new ScanCallback() {

                @Override
                public void onScanResult(int callbackType, ScanResult result) {
                    if (callbackType != ScanSettings.CALLBACK_TYPE_ALL_MATCHES) {
                        // Should not happen.
                        Log.e(TAG, "LE Scan has already started");
                        return;
                    }
                    ScanRecord scanRecord = result.getScanRecord();
                    if (scanRecord == null) {
                        return;
                    }
                    if (serviceUuids != null) {
                        List<ParcelUuid> uuids = new ArrayList<ParcelUuid>();
                        for (UUID uuid : serviceUuids) {
                            uuids.add(new ParcelUuid(uuid));
                        }
                        List<ParcelUuid> scanServiceUuids = scanRecord.getServiceUuids();
                        if (scanServiceUuids == null || !scanServiceUuids.containsAll(uuids)) {
                            if (DBG)
                                Log.d(TAG, "uuids does not match");
                            return;
                        }
                    }
                    callback.onLeScan(result.getDevice(), result.getRssi(), scanRecord.getBytes());
                }
            };
            ScanSettings settings = new ScanSettings.Builder().setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES).setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();
            List<ScanFilter> filters = new ArrayList<ScanFilter>();
            if (serviceUuids != null && serviceUuids.length > 0) {
                // Note scan filter does not support matching an UUID array so we put one
                // UUID to hardware and match the whole array in callback.
                ScanFilter filter = new ScanFilter.Builder().setServiceUuid(new ParcelUuid(serviceUuids[0])).build();
                filters.add(filter);
            }
            scanner.startScan(filters, settings, scanCallback);
            mLeScanClients.put(callback, scanCallback);
            return true;
        } catch (RemoteException e) {
            Log.e(TAG, "", e);
        }
    }
    return false;
}
Also used : ParcelUuid(android.os.ParcelUuid) BluetoothLeScanner(android.bluetooth.le.BluetoothLeScanner) ScanResult(android.bluetooth.le.ScanResult) ScanSettings(android.bluetooth.le.ScanSettings) ScanFilter(android.bluetooth.le.ScanFilter) ArrayList(java.util.ArrayList) ScanCallback(android.bluetooth.le.ScanCallback) UUID(java.util.UUID) RemoteException(android.os.RemoteException) ScanRecord(android.bluetooth.le.ScanRecord) RequiresPermission(android.annotation.RequiresPermission)

Aggregations

ScanSettings (android.bluetooth.le.ScanSettings)24 BluetoothLeScanner (android.bluetooth.le.BluetoothLeScanner)18 ScanFilter (android.bluetooth.le.ScanFilter)14 ScanCallback (android.bluetooth.le.ScanCallback)13 ScanResult (android.bluetooth.le.ScanResult)13 BluetoothAdapter (android.bluetooth.BluetoothAdapter)9 ArrayList (java.util.ArrayList)7 List (java.util.List)7 ParcelUuid (android.os.ParcelUuid)6 RequiresPermission (android.annotation.RequiresPermission)5 ScanRecord (android.bluetooth.le.ScanRecord)5 Message (android.os.Message)5 RemoteException (android.os.RemoteException)5 UUID (java.util.UUID)5 TargetApi (android.annotation.TargetApi)2 PendingIntent (android.app.PendingIntent)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 SuppressLint (android.annotation.SuppressLint)1 BluetoothManager (android.bluetooth.BluetoothManager)1 Intent (android.content.Intent)1