コード例 #1
0
        protected override async Task ScanAsync(CancellationToken cancellationToken)
        {
            // start a scan if bluetooth is present and enabled
            if (BluetoothAdapter.DefaultAdapter?.IsEnabled ?? false)
            {
                try
                {
                    ScanFilter scanFilter = new ScanFilter.Builder()
                                            .SetServiceUuid(new ParcelUuid(_deviceIdService.Uuid))
                                            .Build();

                    List <ScanFilter> scanFilters = new List <ScanFilter>(new[] { scanFilter });

                    ScanSettings.Builder scanSettingsBuilder = new ScanSettings.Builder()
                                                               .SetScanMode(global::Android.Bluetooth.LE.ScanMode.Balanced);

                    // return batched scan results periodically if supported on the BLE chip
                    if (BluetoothAdapter.DefaultAdapter.IsOffloadedScanBatchingSupported)
                    {
                        scanSettingsBuilder.SetReportDelay((long)(ScanDurationMS / 2.0));
                    }

                    // start a fresh manager delegate to collect/read results
                    _bluetoothScannerCallback = new AndroidBluetoothClientScannerCallback(_deviceIdService, _deviceIdCharacteristic, this);

                    BluetoothAdapter.DefaultAdapter.BluetoothLeScanner.StartScan(scanFilters, scanSettingsBuilder.Build(), _bluetoothScannerCallback);

                    TaskCompletionSource <bool> scanCompletionSource = new TaskCompletionSource <bool>();

                    cancellationToken.Register(() =>
                    {
                        try
                        {
                            BluetoothAdapter.DefaultAdapter.BluetoothLeScanner.StopScan(_bluetoothScannerCallback);
                        }
                        catch (Exception ex)
                        {
                            SensusServiceHelper.Get().Logger.Log("Exception while stopping scan:  " + ex.Message, LoggingLevel.Normal, GetType());
                        }
                        finally
                        {
                            scanCompletionSource.TrySetResult(true);
                        }
                    });

                    await scanCompletionSource.Task;
                }
                catch (Exception ex)
                {
                    SensusServiceHelper.Get().Logger.Log("Exception while scanning:  " + ex.Message, LoggingLevel.Normal, GetType());
                }
            }
        }