Advertisement
Guest User

Untitled

a guest
Apr 26th, 2017
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.32 KB | None | 0 0
  1. // Legacy Bluetooth API ( < 21)
  2. private BluetoothAdapter mBluetoothAdapter;
  3. private BluetoothAdapter.LeScanCallback mLeScanCallback;
  4. // Modern Bluetooth API (>= 21)
  5. private ScanCallback mScanCallback;
  6. private BluetoothLeScanner mLEScanner;
  7.  
  8. @TargetApi(21)
  9. private void initBluetooth(Activity activity) {
  10. mActivity = new WeakReference<Activity>(activity);
  11.  
  12. final BluetoothManager bluetoothManager =
  13. (BluetoothManager) mActivity.get().getSystemService(Context.BLUETOOTH_SERVICE);
  14. mBluetoothAdapter = bluetoothManager.getAdapter();
  15.  
  16. if (Build.VERSION.SDK_INT < 21) {
  17. mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
  18. @Override
  19. public void onLeScan(final BluetoothDevice device, int rssi,
  20. byte[] scanRecord) {
  21. mActivity.get().runOnUiThread(new Runnable() {
  22. @Override
  23. public void run() {
  24. Log.i("onLeScan", device.toString());
  25. connectToDevice(device);
  26. }
  27. });
  28. }
  29. };
  30. } else {
  31. mScanCallback = new ScanCallback() {
  32. @Override
  33. public void onScanResult(int callbackType, ScanResult result) {
  34. Log.d("result", result.toString());
  35. BluetoothDevice btDevice = result.getDevice();
  36. connectToDevice(btDevice);
  37. }
  38.  
  39. @Override
  40. public void onBatchScanResults(List<ScanResult> results) {
  41. for (ScanResult sr : results) {
  42. Log.d("ScanResult - Results", sr.toString());
  43. }
  44. }
  45.  
  46. @Override
  47. public void onScanFailed(int errorCode) {
  48. Log.e("Scan Failed", "Error Code: " + errorCode);
  49. }
  50. };
  51. }
  52. }
  53.  
  54. /**
  55. * start and stop Bluetooth LE scanning
  56. * This will use the legacy API before Lollipop (21)
  57. * @param enable scanning active or not
  58. */
  59. private void scanLeDevice(final boolean enable) {
  60. Log.d("scanLeDevice", "enable="+enable);
  61. if (enable) {
  62. mHandler.postDelayed(new Runnable() {
  63. @Override
  64. public void run() {
  65. if (Build.VERSION.SDK_INT < 21) {
  66. mBluetoothAdapter.stopLeScan(mLeScanCallback);
  67. } else {
  68. mLEScanner.stopScan(mScanCallback);
  69.  
  70. }
  71. }
  72. }, SCAN_PERIOD);
  73. if (Build.VERSION.SDK_INT < 21) {
  74. mBluetoothAdapter.startLeScan(mLeScanCallback);
  75. } else {
  76. mLEScanner.startScan(filters, settings, mScanCallback);
  77. }
  78. } else {
  79. if (Build.VERSION.SDK_INT < 21) {
  80. mBluetoothAdapter.stopLeScan(mLeScanCallback);
  81. } else {
  82. mLEScanner.stopScan(mScanCallback);
  83. }
  84. }
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement