Android 8.0蓝牙LE:断开连接后在扫描中不再可发现设备

时间:2018-06-19 20:48:34

标签: c# android xamarin.android bluetooth-lowenergy

扫描,连接和断开设备连接后,除非重新启动该设备,否则该设备将不再出现在新的扫描结果中。

我的扫描代码如下:

    private void startScan()
    {
        if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
        {
            var scanFilter = new List<ScanFilter>
            {
                new ScanFilter.Builder().SetServiceUuid(Constants.Bluetooth.ServiceId.ToParcelUuid()).Build()
            };

            var scanSettingsBuilder = new ScanSettings.Builder()
                .SetScanMode(ScanMode.Balanced);

            if (Build.VERSION.SdkInt >= BuildVersionCodes.M)
            {
                scanSettingsBuilder
                    .SetCallbackType(ScanCallbackType.AllMatches)
                    .SetMatchMode(BluetoothScanMatchMode.Aggressive);
            }

            if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
            {
                scanSettingsBuilder
                    .SetLegacy(true);
            }

            var scanSettings = scanSettingsBuilder.Build();

            _androidAdapter.BluetoothLeScanner.StartScan(scanFilter, scanSettings, _androidScanCallback);
        }
        else
        {
            _androidAdapter.StartLeScan(_androidPreLollipopScanCallback);
        }
    }

我的回调代码如下:

internal class AndroidScanCallback : ScanCallback
{
    private readonly BluetoothManager _bluetoothManager;
    private readonly AndroidBacBluetoothAdapter _adapter;
    private readonly Context _context;

    public AndroidScanCallback(AndroidBacBluetoothAdapter adapter, Context context, BluetoothManager bluetoothManager)
    {
        _adapter = adapter;
        _context = context;
        _bluetoothManager = bluetoothManager;
    }

    public override void OnScanResult(ScanCallbackType callbackType, ScanResult result)
    {
        base.OnScanResult(callbackType, result);

        if (result.Device.Type != BluetoothDeviceType.Le || string.IsNullOrEmpty(result.Device.Name)) return;

        if (callbackType == ScanCallbackType.MatchLost)
        {
            _adapter.RemoveDevices(new List<string>{result.Device.Address});
        }
        else
        {
            OnBatchScanResults(new List<ScanResult> {result});
        }
    }

    public override void OnBatchScanResults(IList<ScanResult> results)
    {
        base.OnBatchScanResults(results);

        _adapter.AddDevices(results);
    }

    public override void OnScanFailed(ScanFailure errorCode)
    {
        base.OnScanFailed(errorCode);

        if (errorCode != ScanFailure.AlreadyStarted)
        {
            _adapter.StopScan();
        }
    }
}

我尝试过的一些事情:

  • 删除过滤器
  • 清理所有未连接的Gatt(关闭并处置)
  • 一个人呆着
  • 没有旧设置

奇怪的是,这一切都可以在Android 7.1上运行,所以我不确定添加了什么新行为来保证这种新行为。任何帮助将不胜感激。

0 个答案:

没有答案