Java 类android.bluetooth.le.ScanCallback 实例源码

项目:NobleAries    文件:Chores.java   
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;
}
项目:RxAndroidBle    文件:ScanOperationApi21.java   
@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;
    }
}
项目:SensorTag-Accelerometer    文件:ScanFragment.java   
@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();
}
项目:igrow-android    文件:DeviceScanActivity.java   
@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);
}
项目:igrow-android    文件:BluetoothLeScanL21Proxy.java   
@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);
        }
    };
}
项目:NobleAries    文件:Chores.java   
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;
}
项目:android-buruberi    文件:LowEnergyScanException.java   
/**
 * 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;
    }
}
项目:miband-sdk-android    文件:MiBand.java   
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);
}
项目:android-ble    文件:BTLEScannerOld.java   
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;
    }
}
项目:android-ble    文件:BTLEScannerOld.java   
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);
    }
}
项目:mDL-ILP    文件:BTConnection.java   
@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.");
                }
            }
        };
}
项目:KB_1711    文件:MainActivity.java   
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);
        }
    };
}
项目:KB_1711    文件:MainActivity.java   
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);
        }
    };
}
项目:mobly-bundled-snippets    文件:BluetoothLeScannerSnippet.java   
/**
 * 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);
}
项目:mobly-bundled-snippets    文件:BluetoothLeScannerSnippet.java   
@Override
public void shutdown() {
    for (ScanCallback callback : mScanCallbacks.values()) {
        mScanner.stopScan(callback);
    }
    mScanCallbacks.clear();
}
项目:mobly-bundled-snippets    文件:MbsEnums.java   
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();
}
项目:Quick-Bluetooth-LE    文件:BLEClient.java   
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;
}
项目:AndroidSensors    文件:BLEMeasurementsGatherer.java   
@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);
}
项目:AndroidSensors    文件:BLEMeasurementsGatherer.java   
@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));
        }
    };
}
项目:AndroidSensors    文件:BLEMeasurementsGatherer.java   
@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);
}
项目:AndroidSensors    文件:BLEMeasurementsGatherer.java   
@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);
        }
    });
}
项目:RxAndroidBle    文件:ScanOperationApi21.java   
@Override
boolean startScan(RxBleAdapterWrapper rxBleAdapterWrapper, ScanCallback scanCallback) {
    rxBleAdapterWrapper.startLeScan(
            androidScanObjectsConverter.toNativeFilters(scanFilters),
            androidScanObjectsConverter.toNativeSettings(scanSettings),
            scanCallback
    );
    return true;
}
项目:RxAndroidBle    文件:RxBleAdapterWrapper.java   
@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);
}
项目:AsteroidOSSync    文件:P_BluetoothCrashResolver.java   
/**
 * 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();
        }
    }
}
项目:xDrip    文件:BluetoothGlucoseMeter.java   
@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?
                }
            }
        };
    }
}
项目:xDrip-plus    文件:BluetoothGlucoseMeter.java   
@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?
                }
            }
        };
    }
}
项目:Quick-Bluetooth-LE    文件:BLEClient.java   
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;
}
项目:Android-BLE-Library    文件:BLEScanner.java   
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();
}
项目:miband-android    文件:MiBand.java   
/**
 * 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();
        }
    };
}
项目:RxBleGattManager    文件:RxBleScanner.java   
@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);
}
项目:android-buruberi    文件:ShadowBluetoothLeScanner.java   
@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);
}
项目:android-buruberi    文件:ShadowBluetoothLeScanner.java   
@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);
}
项目:miband-sdk-android    文件:MiBand.java   
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);
}
项目:SweetBlue    文件:P_BluetoothCrashResolver.java   
/**
 * 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();
        }
    }
}
项目:divertsy-client    文件:BLEScanner.java   
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;
            }
        }
    };
}
项目:igrow-android    文件:DeviceScanActivity.java   
@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();
}
项目:RxAndroidBle    文件:ScanOperationApi21.java   
@Override
void stopScan(RxBleAdapterWrapper rxBleAdapterWrapper, ScanCallback scanCallback) {
    rxBleAdapterWrapper.stopLeScan(scanCallback);
}
项目:RxAndroidBle    文件:RxBleAdapterWrapper.java   
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public void startLeScan(List<ScanFilter> scanFilters, ScanSettings scanSettings, ScanCallback scanCallback) {
    bluetoothAdapter.getBluetoothLeScanner().startScan(scanFilters, scanSettings, scanCallback);
}
项目:BLECommunication    文件:BLEUtil.java   
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);
        }
    }
项目:BLECommunication    文件:BLEUtil.java   
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);
        }
    }