Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Legacy Bluetooth API ( < 21)
- private BluetoothAdapter mBluetoothAdapter;
- private BluetoothAdapter.LeScanCallback mLeScanCallback;
- // Modern Bluetooth API (>= 21)
- private ScanCallback mScanCallback;
- private BluetoothLeScanner mLEScanner;
- @TargetApi(21)
- private void initBluetooth(Activity activity) {
- mActivity = new WeakReference<Activity>(activity);
- final BluetoothManager bluetoothManager =
- (BluetoothManager) mActivity.get().getSystemService(Context.BLUETOOTH_SERVICE);
- mBluetoothAdapter = bluetoothManager.getAdapter();
- if (Build.VERSION.SDK_INT < 21) {
- mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
- @Override
- public void onLeScan(final BluetoothDevice device, int rssi,
- byte[] scanRecord) {
- mActivity.get().runOnUiThread(new Runnable() {
- @Override
- public void run() {
- Log.i("onLeScan", device.toString());
- connectToDevice(device);
- }
- });
- }
- };
- } else {
- mScanCallback = new ScanCallback() {
- @Override
- public void onScanResult(int callbackType, ScanResult result) {
- Log.d("result", result.toString());
- BluetoothDevice btDevice = result.getDevice();
- connectToDevice(btDevice);
- }
- @Override
- public void onBatchScanResults(List<ScanResult> results) {
- for (ScanResult sr : results) {
- Log.d("ScanResult - Results", sr.toString());
- }
- }
- @Override
- public void onScanFailed(int errorCode) {
- Log.e("Scan Failed", "Error Code: " + errorCode);
- }
- };
- }
- }
- /**
- * start and stop Bluetooth LE scanning
- * This will use the legacy API before Lollipop (21)
- * @param enable scanning active or not
- */
- private void scanLeDevice(final boolean enable) {
- Log.d("scanLeDevice", "enable="+enable);
- if (enable) {
- mHandler.postDelayed(new Runnable() {
- @Override
- public void run() {
- if (Build.VERSION.SDK_INT < 21) {
- mBluetoothAdapter.stopLeScan(mLeScanCallback);
- } else {
- mLEScanner.stopScan(mScanCallback);
- }
- }
- }, SCAN_PERIOD);
- if (Build.VERSION.SDK_INT < 21) {
- mBluetoothAdapter.startLeScan(mLeScanCallback);
- } else {
- mLEScanner.startScan(filters, settings, mScanCallback);
- }
- } else {
- if (Build.VERSION.SDK_INT < 21) {
- mBluetoothAdapter.stopLeScan(mLeScanCallback);
- } else {
- mLEScanner.stopScan(mScanCallback);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement