Java Code Examples for android.bluetooth.le.ScanCallback

The following are top voted examples for showing how to use android.bluetooth.le.ScanCallback. 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: SensorTag-Accelerometer   File: ScanFragment.java   View source code 8 votes vote down vote up
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // initialize the right scan callback for the current API level
    if (Build.VERSION.SDK_INT >= 21) {
        mScanCallback = new ScanCallback() {
            @Override
            public void onScanResult(int callbackType, ScanResult result) {
                super.onScanResult(callbackType, result);
                mRecyclerViewAdapter.addDevice(result.getDevice().getAddress());
            }
        };
    } else {
        mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
            @Override
            public void onLeScan(BluetoothDevice bluetoothDevice, int i, byte[] bytes) {
                mRecyclerViewAdapter.addDevice(bluetoothDevice.getAddress());
            }
        };
    }

    // initialize bluetooth manager & adapter
    BluetoothManager manager = (BluetoothManager) getActivity().getSystemService(Context.BLUETOOTH_SERVICE);
    mBluetoothAdapter = manager.getAdapter();
}
 
Example 2
Project: RxAndroidBle   File: ScanOperationApi21.java   View source code 8 votes vote down vote up
@BleScanException.Reason private static int errorCodeToBleErrorCode(int errorCode) {
    switch (errorCode) {
        case ScanCallback.SCAN_FAILED_ALREADY_STARTED:
            return BleScanException.SCAN_FAILED_ALREADY_STARTED;
        case ScanCallback.SCAN_FAILED_APPLICATION_REGISTRATION_FAILED:
            return BleScanException.SCAN_FAILED_APPLICATION_REGISTRATION_FAILED;
        case ScanCallback.SCAN_FAILED_FEATURE_UNSUPPORTED:
            return BleScanException.SCAN_FAILED_FEATURE_UNSUPPORTED;
        case ScanCallback.SCAN_FAILED_INTERNAL_ERROR:
            return BleScanException.SCAN_FAILED_INTERNAL_ERROR;
        case 5: // ScanCallback.SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES
            return BleScanException.SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES;
        default:
            RxBleLog.w("Encountered unknown scanning error code: %d -> check android.bluetooth.le.ScanCallback");
            return BleScanException.UNKNOWN_ERROR_CODE;
    }
}
 
Example 3
Project: NobleAries   File: Chores.java   View source code 7 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 4
Project: igrow-android   File: DeviceScanActivity.java   View source code 6 votes vote down vote up
@Override
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@SuppressWarnings("deprecation")
protected void onListItemClick(ListView l, View v, int position, long id) {
    final BluetoothDevice device = mLeDeviceListAdapter.getDevice(position);
    if (device == null) return;
    final Intent intent = new Intent(this, DeviceControlActivity.class);
    intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_NAME, device.getName());
    intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_ADDRESS, device.getAddress());
    if (mScanning) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mBluetoothLeScanner.stopScan(new ScanCallback() {});
        } else {
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
        }
        mScanning = false;
    }
    startActivity(intent);
}
 
Example 5
Project: igrow-android   File: BluetoothLeScanL21Proxy.java   View source code 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public BluetoothLeScanL21Proxy(BluetoothAdapter bluetoothAdapter) {

    mBluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();

    mLeScanCallback = new ScanCallback() {

        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);
        }

        @Override
        public void onBatchScanResults(List<ScanResult> results) {
            super.onBatchScanResults(results);
        }

        @Override
        public void onScanFailed(int errorCode) {
            super.onScanFailed(errorCode);
        }
    };
}
 
Example 6
Project: NobleAries   File: Chores.java   View source code 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-buruberi   File: LowEnergyScanException.java   View source code 6 votes vote down vote up
/**
 * Returns the corresponding constant name for a
 * given {@code ScanCallback#SCAN_FAILED_*} value.
 */
public static String scanFailureToString(int scanFailure) {
    switch (scanFailure) {
        case ScanCallback.SCAN_FAILED_ALREADY_STARTED:
            return "SCAN_FAILED_ALREADY_STARTED";

        case ScanCallback.SCAN_FAILED_APPLICATION_REGISTRATION_FAILED:
            return "SCAN_FAILED_APPLICATION_REGISTRATION_FAILED";

        case ScanCallback.SCAN_FAILED_INTERNAL_ERROR:
            return "SCAN_FAILED_INTERNAL_ERROR";

        case ScanCallback.SCAN_FAILED_FEATURE_UNSUPPORTED:
            return "SCAN_FAILED_FEATURE_UNSUPPORTED";

        default:
            return "UNKNOWN: " + scanFailure;
    }
}
 
Example 8
Project: miband-sdk-android   File: MiBand.java   View source code 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 9
Project: miband-sdk-android   File: MiBand.java   View source code 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 10
Project: android-ble   File: BTLEScannerOld.java   View source code 6 votes vote down vote up
public BTLEScannerOld(BluetoothAdapter bluetoothAdapter, Callback callback) {
    this.bluetoothAdapter = bluetoothAdapter;
    this.leScanCallback = callback::onScan;

    if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
        this.leScanner = bluetoothAdapter.getBluetoothLeScanner();

        this.scanCallback = new ScanCallback() {
            @Override
            public void onScanResult(int callbackType, ScanResult result) {
                if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
                    callback.onScan(result.getDevice(), result.getRssi(), result.getScanRecord().getBytes());
                }

                super.onScanResult(callbackType, result);
            }
        };
    } else {
        this.leScanner = null;
        this.scanCallback = null;
    }
}
 
Example 11
Project: android-ble   File: BTLEScannerOld.java   View source code 6 votes vote down vote up
public void startScan() {
    if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
        leScanner.startScan(new android.bluetooth.le.ScanCallback() {
            @Override
            public void onScanResult(int callbackType, ScanResult result) {

                super.onScanResult(callbackType, result);
            }

            @Override
            public void onBatchScanResults(List<ScanResult> results) {
                super.onBatchScanResults(results);
            }
        });
    } else {
        bluetoothAdapter.startLeScan(leScanCallback);
    }
}
 
Example 12
Project: mDL-ILP   File: BTConnection.java   View source code 5 votes vote down vote up
@NonNull
private ScanCallback getScanCallback(final byte[] serviceData) {
    return new ScanCallback() {
            @Override
            public void onScanResult(int callbackType, ScanResult result) {
                processResult(result);
            }

            @Override
            public void onBatchScanResults(List<ScanResult> results) {
                for (ScanResult s: results) {
                    processResult(s);
                }
            }

            @Override
            public void onScanFailed(int errorCode) {
                Log.d(TAG, "Scan failed: " + String.valueOf(errorCode));
            }

            public void processResult(ScanResult sr) {
                Log.d(TAG, "Found device " + sr.getDevice().getName() + "(" + sr.getDevice().getAddress() + ")");

                /* confirm correct connection key */
                byte[] sd = sr.getScanRecord().getServiceData(Constants.SERVICE_pUUID);
                if (sd != null) {
                    if (Arrays.equals(sd, serviceData)) {
                        BTConnection.this.stopScan();
                        transfer.startServer(sr.getDevice());
                    } else {
                        Log.d(TAG, "Incorrect service data: " + new String(sd) + " instead of " + new String(serviceData) + ". Continuing.");
                    }
                } else {
                    Log.d(TAG, "No service data received -- continuing.");
                }
            }
        };
}
 
Example 13
Project: KB_1711   File: MainActivity.java   View source code 5 votes vote down vote up
private ScanCallback initCallbacks() {
    return new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);

            if (result != null && result.getDevice() != null) {
                if (isAdded(result.getDevice())) {
                    // No add
                } else {
                    saveDevice(result.getDevice());
                }
            }

        }

        @Override
        public void onBatchScanResults(List<ScanResult> results) {
            super.onBatchScanResults(results);
        }

        @Override
        public void onScanFailed(int errorCode) {
            super.onScanFailed(errorCode);
        }
    };
}
 
Example 14
Project: KB_1711   File: MainActivity.java   View source code 5 votes vote down vote up
private ScanCallback initCallbacks() {
    return new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);

            if (result != null && result.getDevice() != null) {
                if (isAdded(result.getDevice())) {
                    // No add
                } else {
                    saveDevice(result.getDevice());
                }
            }

        }

        @Override
        public void onBatchScanResults(List<ScanResult> results) {
            super.onBatchScanResults(results);
        }

        @Override
        public void onScanFailed(int errorCode) {
            super.onScanFailed(errorCode);
        }
    };
}
 
Example 15
Project: mobly-bundled-snippets   File: BluetoothLeScannerSnippet.java   View source code 5 votes vote down vote up
/**
 * Stop a BLE scan.
 *
 * @param callbackId The callbackId corresponding to the {@link
 *     BluetoothLeScannerSnippet#bleStartScan} call that started the scan.
 * @throws BluetoothLeScanSnippetException
 */
@RpcMinSdk(Build.VERSION_CODES.LOLLIPOP_MR1)
@Rpc(description = "Stop a BLE scan.")
public void bleStopScan(String callbackId) throws BluetoothLeScanSnippetException {
    ScanCallback callback = mScanCallbacks.remove(callbackId);
    if (callback == null) {
        throw new BluetoothLeScanSnippetException("No ongoing scan with ID: " + callbackId);
    }
    mScanner.stopScan(callback);
}
 
Example 16
Project: mobly-bundled-snippets   File: BluetoothLeScannerSnippet.java   View source code 5 votes vote down vote up
@Override
public void shutdown() {
    for (ScanCallback callback : mScanCallbacks.values()) {
        mScanner.stopScan(callback);
    }
    mScanCallbacks.clear();
}
 
Example 17
Project: mobly-bundled-snippets   File: MbsEnums.java   View source code 5 votes vote down vote up
private static RpcEnum buildBleScanFailedErrorCodeEnum() {
    RpcEnum.Builder builder = new RpcEnum.Builder();
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        return builder.build();
    }
    return builder.add("SCAN_FAILED_ALREADY_STARTED", ScanCallback.SCAN_FAILED_ALREADY_STARTED)
            .add(
                    "SCAN_FAILED_APPLICATION_REGISTRATION_FAILED",
                    ScanCallback.SCAN_FAILED_APPLICATION_REGISTRATION_FAILED)
            .add(
                    "SCAN_FAILED_FEATURE_UNSUPPORTED",
                    ScanCallback.SCAN_FAILED_FEATURE_UNSUPPORTED)
            .add("SCAN_FAILED_INTERNAL_ERROR", ScanCallback.SCAN_FAILED_INTERNAL_ERROR)
            .build();
}
 
Example 18
Project: Quick-Bluetooth-LE   File: BLEClient.java   View source code 5 votes vote down vote up
public void stopScanning(){
	if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && bleScanner != null && useNewMethod){
		bleScanner.stopScan((ScanCallback) scanCallback);
	}else if(btAdapter != null){
		btAdapter.stopLeScan(leScanCallback);
	}
	scanning = false;
}
 
Example 19
Project: AndroidSensors   File: BLEMeasurementsGatherer.java   View source code 5 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void configureSensorSubscribeAndUnsubscribeBehaviors(FlowableEmitter<SensorRecord> subscriber) {
    List<ScanFilter> scanFilters = initializeScanFilters();
    ScanSettings scanSettings = initializeScanSettings();
    final ScanCallback scanCallback = initializeScanCallbackFor(subscriber);

    startListeningBluetoothMeasurements(scanFilters, scanSettings, scanCallback);
    addUnsuscribeCallbackFor(subscriber, scanCallback);
}
 
Example 20
Project: AndroidSensors   File: BLEMeasurementsGatherer.java   View source code 5 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private ScanCallback initializeScanCallbackFor(final FlowableEmitter<SensorRecord> subscriber){
    return new ScanCallback() {
        @Override
        public void onBatchScanResults(List<ScanResult> results) {
            subscriber.onNext(new BLEMeasurementsRecord(results));
        }
    };
}
 
Example 21
Project: AndroidSensors   File: BLEMeasurementsGatherer.java   View source code 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 22
Project: AndroidSensors   File: BLEMeasurementsGatherer.java   View source code 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 23
Project: RxAndroidBle   File: ScanOperationApi21.java   View source code 5 votes vote down vote up
@Override
boolean startScan(RxBleAdapterWrapper rxBleAdapterWrapper, ScanCallback scanCallback) {
    rxBleAdapterWrapper.startLeScan(
            androidScanObjectsConverter.toNativeFilters(scanFilters),
            androidScanObjectsConverter.toNativeSettings(scanSettings),
            scanCallback
    );
    return true;
}
 
Example 24
Project: RxAndroidBle   File: RxBleAdapterWrapper.java   View source code 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 25
Project: AsteroidOSSync   File: P_BluetoothCrashResolver.java   View source code 5 votes vote down vote up
/**
 * Call this method from your BluetoothAdapter.LeScanCallback method.
 * Doing so is optional, but if you do, this class will be able to count the number of
 * disctinct bluetooth devices scanned, and prevent crashes before they happen.
 *
 * This works very well if the app containing this class is the only one running bluetooth
 * LE scans on the device, or it is constantly doing scans (e.g. is in the foreground for
 * extended periods of time.)
 *
 * This will not work well if the application using this class is only scanning periodically
 * (e.g. when in the background to save battery) and another application is also scanning on
 * the same device, because this class will only get the counts from this application.
 *
 * Future augmentation of this class may improve this by somehow centralizing the list of
 * unique scanned devices.
 *
 * @param device
 */
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public void notifyScannedDevice(P_NativeDeviceLayer device, BluetoothAdapter.LeScanCallback scanner, ScanCallback callback) {
    int oldSize = 0, newSize = 0;

    if (isDebugEnabled()) oldSize = distinctBluetoothAddresses.size();

    distinctBluetoothAddresses.add(device.getAddress());
    if (isDebugEnabled()) {
        newSize = distinctBluetoothAddresses.size();
        if (oldSize != newSize && newSize % 100 == 0) {
            if (isDebugEnabled()) Log.d(TAG, "Distinct bluetooth devices seen: "+distinctBluetoothAddresses.size());
        }
    }
    if (distinctBluetoothAddresses.size()  > getCrashRiskDeviceCount()) {
        if (PREEMPTIVE_ACTION_ENABLED && !recoveryInProgress) {
            Log.w(TAG, "Large number of bluetooth devices detected: "+distinctBluetoothAddresses.size()+" Proactively attempting to clear out address list to prevent a crash");
            Log.w(TAG, "Stopping LE Scan");
            if (scanner != null)
            {
                BluetoothAdapter.getDefaultAdapter().stopLeScan(scanner);
            }
            else
            {
                BluetoothAdapter.getDefaultAdapter().getBluetoothLeScanner().stopScan(callback);
            }
            startRecovery();
            processStateChange();
        }
    }
}
 
Example 26
Project: xDrip   File: BluetoothGlucoseMeter.java   View source code 5 votes vote down vote up
@TargetApi(21)
private void initScanCallback() {
    Log.d(TAG, "init v21 ScanCallback()");

    // v21 version
    if (Build.VERSION.SDK_INT >= 21) {
        mScanCallback = new ScanCallback() {
            @Override
            public void onScanResult(int callbackType, ScanResult result) {
                Log.i(TAG, "onScanResult result: " + result.toString());
                final BluetoothDevice btDevice = result.getDevice();
                scanLeDevice(false); // stop scanning
                connect(btDevice.getAddress());
            }

            @Override
            public void onBatchScanResults(List<ScanResult> results) {
                for (ScanResult sr : results) {
                    Log.i("ScanResult - Results", sr.toString());
                }
            }

            @Override
            public void onScanFailed(int errorCode) {
                Log.e(TAG, "Scan Failed Error Code: " + errorCode);
                if (errorCode == 1) {
                    Log.e(TAG, "Already Scanning: "); // + isScanning);
                    //isScanning = true;
                } else if (errorCode == 2) {
                    // reset bluetooth?
                }
            }
        };
    }
}
 
Example 27
Project: xDrip-plus   File: BluetoothGlucoseMeter.java   View source code 5 votes vote down vote up
@TargetApi(21)
private void initScanCallback() {
    Log.d(TAG, "init v21 ScanCallback()");

    // v21 version
    if (Build.VERSION.SDK_INT >= 21) {
        mScanCallback = new ScanCallback() {
            @Override
            public void onScanResult(int callbackType, ScanResult result) {
                Log.i(TAG, "onScanResult result: " + result.toString());
                final BluetoothDevice btDevice = result.getDevice();
                scanLeDevice(false); // stop scanning
                connect(btDevice.getAddress());
            }

            @Override
            public void onBatchScanResults(List<ScanResult> results) {
                for (ScanResult sr : results) {
                    Log.i("ScanResult - Results", sr.toString());
                }
            }

            @Override
            public void onScanFailed(int errorCode) {
                Log.e(TAG, "Scan Failed Error Code: " + errorCode);
                if (errorCode == 1) {
                    Log.e(TAG, "Already Scanning: "); // + isScanning);
                    //isScanning = true;
                } else if (errorCode == 2) {
                    // reset bluetooth?
                }
            }
        };
    }
}
 
Example 28
Project: Quick-Bluetooth-LE   File: BLEClient.java   View source code 5 votes vote down vote up
public void stopScanning(){
	if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && bleScanner != null && useNewMethod){
		bleScanner.stopScan((ScanCallback) scanCallback);
	}else if(btAdapter != null){
		btAdapter.stopLeScan(leScanCallback);
	}
	scanning = false;
}
 
Example 29
Project: Android-BLE-Library   File: BLEScanner.java   View source code 5 votes vote down vote up
private void initScanData() {
    scanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);
            Log.i(TAG, "onScanResult" + result);
            String address = result.getDevice().getAddress();
            String name;
            ScanRecord scanRecord = result.getScanRecord();
            name = scanRecord == null ? "unknown" : scanRecord.getDeviceName();
            scanResultListener.onResultReceived(name, address);
        }

        @Override
        public void onBatchScanResults(List<ScanResult> results) {
            super.onBatchScanResults(results);
            Log.e(TAG, "onBatchScanResults");
        }

        @Override
        public void onScanFailed(int errorCode) {
            super.onScanFailed(errorCode);
            Log.e(TAG, "onScanFailed");
            scanResultListener.onScanFailed(errorCode);
        }
    };
    filters = new ArrayList<>();
    filters.add(new ScanFilter.Builder().setServiceUuid(ParcelUuid.fromString(BLEProfile.UUID_SERVICE)).build());
    scanSettings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();
}
 
Example 30
Project: miband-android   File: MiBand.java   View source code 5 votes vote down vote up
/**
 * Creates {@link ScanCallback} instance
 *
 * @param subscriber Subscriber
 * @return ScanCallback instance
 */
private ScanCallback getScanCallback(ObservableEmitter<? super ScanResult> subscriber) {
    return new ScanCallback() {
        @Override
        public void onScanFailed(int errorCode) {
            subscriber.onError(new Exception("Scan failed, error code " + errorCode));
        }

        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            subscriber.onNext(result);
            subscriber.onComplete();
        }
    };
}
 
Example 31
Project: RxBleGattManager   File: RxBleScanner.java   View source code 5 votes vote down vote up
@Override public void call(Subscriber<? super BleDevice> subscriber) {
    setAdapter();
    setScanner();

    if (!IS_BLE_SUPPORTED) {
        subscriber.onError(new ScanException(STATUS_BLE_NOT_SUPPORTED));
    }
    if (!isBleEnabled()) {
        subscriber.onError(new ScanException(STATUS_BLE_NOT_ENABLED));
    }

    final ScanCallback callback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);
            BleDevice discoveredDevice = BleDevice.create(result);
            subscriber.onNext(discoveredDevice);
        }
    };

    subscriber.add(new MainThreadSubscription() {
        @Override protected void onUnsubscribe() {
            if (scanner != null && IS_BLE_SUPPORTED && isBleEnabled()) {
                scanner.stopScan(callback);
                scanner = null;
            }
        }
    });
    scanner.stopScan(callback);
    scanner.startScan(callback);
}
 
Example 32
Project: android-buruberi   File: ShadowBluetoothLeScanner.java   View source code 5 votes vote down vote up
@Implementation
@RequiresPermission(Manifest.permission.BLUETOOTH)
public void startScan(List<ScanFilter> filters,
                      ScanSettings settings,
                      ScanCallback callback) {
    if (adapter.getState() != BluetoothAdapter.STATE_ON) {
        throw new IllegalStateException("BT Adapter is not turned ON");
    }

    scanCallbacks.add(callback);
}
 
Example 33
Project: android-buruberi   File: ShadowBluetoothLeScanner.java   View source code 5 votes vote down vote up
@Implementation
@RequiresPermission(Manifest.permission.BLUETOOTH)
public void stopScan(ScanCallback callback) {
    if (adapter.getState() != BluetoothAdapter.STATE_ON) {
        throw new IllegalStateException("BT Adapter is not turned ON");
    }

    scanCallbacks.remove(callback);
}
 
Example 34
Project: SweetBlue   File: P_BluetoothCrashResolver.java   View source code 5 votes vote down vote up
/**
 * Call this method from your BluetoothAdapter.LeScanCallback method.
 * Doing so is optional, but if you do, this class will be able to count the number of
 * disctinct bluetooth devices scanned, and prevent crashes before they happen.
 *
 * This works very well if the app containing this class is the only one running bluetooth
 * LE scans on the device, or it is constantly doing scans (e.g. is in the foreground for
 * extended periods of time.)
 *
 * This will not work well if the application using this class is only scanning periodically
 * (e.g. when in the background to save battery) and another application is also scanning on
 * the same device, because this class will only get the counts from this application.
 *
 * Future augmentation of this class may improve this by somehow centralizing the list of
 * unique scanned devices.
 *
 * @param device
 */
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public void notifyScannedDevice(P_NativeDeviceLayer device, BluetoothAdapter.LeScanCallback scanner, ScanCallback callback) {
    int oldSize = 0, newSize = 0;

    if (isDebugEnabled()) oldSize = distinctBluetoothAddresses.size();

    synchronized (distinctBluetoothAddresses)
    {
        distinctBluetoothAddresses.add(device.getAddress());
    }
    if (isDebugEnabled()) {
        newSize = distinctBluetoothAddresses.size();
        if (oldSize != newSize && newSize % 100 == 0) {
            if (isDebugEnabled()) Log.d(TAG, "Distinct bluetooth devices seen: "+distinctBluetoothAddresses.size());
        }
    }
    if (distinctBluetoothAddresses.size()  > getCrashRiskDeviceCount()) {
        if (PREEMPTIVE_ACTION_ENABLED && !recoveryInProgress) {
            Log.w(TAG, "Large number of bluetooth devices detected: "+distinctBluetoothAddresses.size()+" Proactively attempting to clear out address list to prevent a crash");
            Log.w(TAG, "Stopping LE Scan");
            if (scanner != null)
            {
                BluetoothAdapter.getDefaultAdapter().stopLeScan(scanner);
            }
            else
            {
                BluetoothAdapter.getDefaultAdapter().getBluetoothLeScanner().stopScan(callback);
            }
            startRecovery();
            processStateChange();
        }
    }
}
 
Example 35
Project: divertsy-client   File: BLEScanner.java   View source code 4 votes vote down vote up
public BLEScanner(final Activity activity, int requestEnableBluetooth, @NonNull OnClosestChangedListener onClosestChangedListener) {
    mRequestEnableBluetooth = requestEnableBluetooth;
    mOnClosestChangedListener = onClosestChangedListener;
    init(activity);
    scanFilters = new ArrayList<>();
    scanFilters.add(new ScanFilter.Builder().setServiceUuid(EDDYSTONE_SERVICE_UUID).build());
    scanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            ScanRecord scanRecord = result.getScanRecord();
            if (scanRecord == null) {
                return;
            }

            String deviceAddress = result.getDevice().getAddress();
            Beacon beacon;
            if (!deviceToBeaconMap.containsKey(deviceAddress)) {
                beacon = new Beacon(deviceAddress, result.getRssi());
                deviceToBeaconMap.put(deviceAddress, beacon);
            } else {
                deviceToBeaconMap.get(deviceAddress).lastSeenTimestamp = System.currentTimeMillis();
                deviceToBeaconMap.get(deviceAddress).rssi = result.getRssi();
            }

            byte[] serviceData = scanRecord.getServiceData(EDDYSTONE_SERVICE_UUID);
            validateServiceData(deviceAddress, serviceData);

            findClosest();
        }

        @Override
        public void onScanFailed(int errorCode) {
            switch (errorCode) {
                case SCAN_FAILED_ALREADY_STARTED:
                    logErrorAndShowToast(activity, "SCAN_FAILED_ALREADY_STARTED");
                    break;
                case SCAN_FAILED_APPLICATION_REGISTRATION_FAILED:
                    logErrorAndShowToast(activity, "SCAN_FAILED_APPLICATION_REGISTRATION_FAILED");
                    break;
                case SCAN_FAILED_FEATURE_UNSUPPORTED:
                    logErrorAndShowToast(activity, "SCAN_FAILED_FEATURE_UNSUPPORTED");
                    break;
                case SCAN_FAILED_INTERNAL_ERROR:
                    logErrorAndShowToast(activity, "SCAN_FAILED_INTERNAL_ERROR");
                    break;
                default:
                    logErrorAndShowToast(activity, "Scan failed, unknown error code");
                    break;
            }
        }
    };
}
 
Example 36
Project: igrow-android   File: DeviceScanActivity.java   View source code 4 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@SuppressWarnings("deprecation")
private void scanLeDevice(final boolean enable) {
    if (enable) {
        // Stops scanning after a pre-defined scan period.
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mScanning = false;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    mBluetoothLeScanner.stopScan(new ScanCallback() {});
                } else {
                    mBluetoothAdapter.stopLeScan(mLeScanCallback);
                }
                invalidateOptionsMenu();
            }
        }, SCAN_PERIOD);

        mScanning = true;
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mBluetoothLeScanner
                    .startScan(null, mScanSettings, new ScanCallback() {
                        @Override
                        public void onScanResult(int callbackType, ScanResult result) {
                            super.onScanResult(callbackType, result);
                        }

                        @Override
                        public void onBatchScanResults(List<ScanResult> results) {
                            super.onBatchScanResults(results);
                        }

                        @Override
                        public void onScanFailed(int errorCode) {
                            super.onScanFailed(errorCode);
                            if (Log.isLoggable(TAG, Log.ERROR)) {
                                Log.e(TAG, "Failed to start BT LE Scan: " + errorCode);
                            }
                        }
                    });
        } else {
            mBluetoothAdapter.startLeScan(mLeScanCallback);
        }
    } else {
        mScanning = false;
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mBluetoothLeScanner.stopScan(new ScanCallback() {});
        } else {
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
        }
    }
    invalidateOptionsMenu();
}
 
Example 37
Project: RxAndroidBle   File: ScanOperationApi21.java   View source code 4 votes vote down vote up
@Override
void stopScan(RxBleAdapterWrapper rxBleAdapterWrapper, ScanCallback scanCallback) {
    rxBleAdapterWrapper.stopLeScan(scanCallback);
}
 
Example 38
Project: RxAndroidBle   File: RxBleAdapterWrapper.java   View source code 4 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public void startLeScan(List<ScanFilter> scanFilters, ScanSettings scanSettings, ScanCallback scanCallback) {
    bluetoothAdapter.getBluetoothLeScanner().startScan(scanFilters, scanSettings, scanCallback);
}
 
Example 39
Project: BLECommunication   File: BLEUtil.java   View source code 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 40
Project: BLECommunication   File: BLEUtil.java   View source code 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);
    	}
    }