BTManager.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using Android.Bluetooth;
  2. using Android.Bluetooth.LE;
  3. using Android.Content;
  4. using Android.OS;
  5. using System;
  6. using System.Collections.Generic;
  7. namespace MyLibrary.Bluetooth
  8. {
  9. public class BLEScanner
  10. {
  11. private BluetoothManager _bluetoothManager;
  12. private BluetoothAdapter _bluetoothAdapter;
  13. private BluetoothLeScanner _bluetoothLeScanner;
  14. private ScanCallback _scanCallback;
  15. public BLEScanner(Context context)
  16. {
  17. _bluetoothManager = (BluetoothManager)context.GetSystemService(Context.BluetoothService);
  18. _bluetoothAdapter = _bluetoothManager.Adapter;
  19. _bluetoothLeScanner = _bluetoothAdapter?.BluetoothLeScanner;
  20. if (_bluetoothLeScanner == null)
  21. {
  22. throw new Exception("Bluetooth LE Scanner is not available.");
  23. }
  24. }
  25. /*
  26. var bleScanner = new BLEScanner(Android.App.Application.Context);
  27. bleScanner.StartScan(
  28. );
  29. // Stop the scan after 10 seconds
  30. Task.Delay(10000).ContinueWith(_ => bleScanner.StopScan());
  31. */
  32. public void StartScan(Action<ScanResult> onDeviceFound, Action onScanStopped = null)
  33. {
  34. _scanCallback = new CustomScanCallback(onDeviceFound, onScanStopped);
  35. _bluetoothLeScanner.StartScan(_scanCallback);
  36. }
  37. public void StopScan()
  38. {
  39. _bluetoothLeScanner?.StopScan(_scanCallback);
  40. }
  41. private class CustomScanCallback : ScanCallback
  42. {
  43. private readonly Action<ScanResult> _onDeviceFound;
  44. private readonly Action _onScanStopped;
  45. public CustomScanCallback(Action<ScanResult> onDeviceFound, Action onScanStopped)
  46. {
  47. _onDeviceFound = onDeviceFound;
  48. _onScanStopped = onScanStopped;
  49. }
  50. public override void OnScanResult(ScanCallbackType callbackType, ScanResult result)
  51. {
  52. base.OnScanResult(callbackType, result);
  53. _onDeviceFound?.Invoke(result);
  54. }
  55. public override void OnScanFailed(ScanFailure errorCode)
  56. {
  57. base.OnScanFailed(errorCode);
  58. _onScanStopped?.Invoke();
  59. throw new Exception($"Scan failed with error code: {errorCode}");
  60. }
  61. }
  62. }
  63. }