首页 > 解决方案 > Xamarin 表单 - 无法扫描 BLE 设备

问题描述

我是 Xamarin 表单和 C# 的新手。我正在尝试使用本机 Xamarin 表单 API 扫描 BLE 设备,并附上代码。我正在使用运行 android 9 的 Xiomi note 5。

using Android.Bluetooth;
using Android.Bluetooth.LE;
using Android.Runtime;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using Xamarin.Forms;


namespace bletest
{
    // Learn more about making custom code visible in the Xamarin.Forms previewer
    // by visiting https://aka.ms/xamarinforms-previewer
    [DesignTimeVisible(false)]


    public class MyScanCallback : ScanCallback
    {
        public override void OnBatchScanResults(IList<ScanResult> results)
        {
            base.OnBatchScanResults(results);
        }

        public override void OnScanResult([GeneratedEnum] ScanCallbackType callbackType, ScanResult result)
        {
            base.OnScanResult(callbackType, result);
        }

        public override void OnScanFailed([GeneratedEnumAttribute] ScanFailure errorCode)
        {
            base.OnScanFailed(errorCode);
        }
    }

    public class newbtle
    {
        private readonly BluetoothAdapter   _ba;
        private readonly BluetoothLeScanner _sc;
        private readonly MyScanCallback     _scCb;
 
        public newbtle()
        {
            _ba = BluetoothAdapter.DefaultAdapter;
            _sc = _ba.BluetoothLeScanner;
            _scCb = new MyScanCallback();

        }

        public  void BleScan()
        {
            if (_ba.Enable() == true)
            {
                _sc.StartScan(_scCb);
            }
        }

        public void BleScanStop()
        {
            _sc.StopScan(_scCb);
            _sc.FlushPendingScanResults(_scCb);
            _ba.Disable();
        }

        public string GetScanMode()
        {
            return _ba.ScanMode.ToString();
        }

        public string GetStateMode()
        {
            return _ba.State.ToString();
        }

    }



    public partial class MainPage : ContentPage
    {
        newbtle bt = new newbtle();

        public MainPage()
        {
            InitializeComponent();
        }

        private void Button_Clicked(object sender, EventArgs e)
        {
            bt.BleScan();
        }

        private void Button_Clicked_1(object sender, EventArgs e)
        {
            bt.BleScanStop();

        }

    }
}

当调用 bt.BleScan 时,不会调用回调,当第二次调用 bt.BleScan 而不关闭扫描仪时,会调用 OnScanFailed 并显示“已激活错误”。

当我在同一环境中的同一台移动设备上运行 BLE explorer 实用程序时,它会扫描几个 BLE 设备。

任何建议可能是什么问题?谢谢

标签: c#androidxamarinbluetooth-lowenergy

解决方案


推荐阅读