c# - 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 设备。
任何建议可能是什么问题?谢谢
解决方案
推荐阅读
- java - -+1 字符串正则表达式检查字符串编号是否同时包含两个符号 java
- ibm-midrange - RPGLE 程序中的记录选择
- python - 使用 scipy 最小化带有参数的函数
- python - 如何使用 f"" 字符串而不是 .format() 打印二进制数?
- java - spring boot 提供嵌套在模板文件夹中的 html 文件
- python - 为什么会出现错误 AttributeError:“WebDriver”对象没有属性“executes_script”
- elasticsearch - 如何将此 elasticsearch 查询从 2.x 转换为 5.x 索引?
- c# - 任务计划程序问题和读取 Excel 文件
- batch-file - TFS 在具有管理员权限的远程服务器上运行批处理脚本
- ios - iOS - 像 WhatsApp 一样保持质量的视频压缩,但使用 Swift 减小了大小