我最近开始使用Xamarin.Forms开发Android和iOS应用程序。我需要使用BLE检测并连接到自定义嵌入式设备,但是直到现在我都没有成功。我尝试使用Plugin.BLE NuGet包,但该应用似乎没有检测到任何设备。但是,它确实响应手机蓝牙连接状态的变化(开/关)。我试图预先配对设备,但没有任何区别。我还尝试使用Play商店中的其他应用程序检查设备,我可以在那里看到相应的设备。代码是在MainPage.xaml.cs
之后从共享项目的InitializeComponent()
运行的。我正在测试应用程序的设备是运行Android 8.1的Google Pixel XL。当我尝试在Android 7上使用三星Galaxy S7时没有任何改变。
这是我使用的代码,直接来自官方文档。
代码示例:
private async void BLE()
{
var ble = CrossBluetoothLE.Current;
var adapter = CrossBluetoothLE.Current.Adapter;
var state = ble.State;
adapter.ScanMode = Plugin.BLE.Abstractions.Contracts.ScanMode.LowLatency;
adapter.ScanTimeout = 5000;
ble.StateChanged += (s, e) =>
{
i++;
this.display.Text = "The bluetooth state changed, iteration " + i;
Debug.WriteLine($"The bluetooth state changed to {e.NewState}");
};
adapter.DeviceDiscovered += (s, a) =>
{
// Debug.WriteLine(a.Device);
eviceList.Add(a.Device.ToString());
Debug.WriteLine("Device list: " + a.Device);
};
adapter.DeviceAdvertised += (s, a) =>
{
Debug.WriteLine("Device advertised: " + a.Device);
};
await adapter.StartScanningForDevicesAsync();
}
权限:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
答案 0 :(得分:0)
几天前我遇到了这个问题,对我来说这是一个权限问题,因为蓝牙需要“位置”权限(就像您在代码中已经拥有的一样),但是从未向用户请求“位置”权限。
为解决此问题,我将此添加到MainActivity.cs文件中,以便在应用启动之前检查/请求所有必需的权限。
private readonly string[] Permissions =
{
Manifest.Permission.Bluetooth,
Manifest.Permission.BluetoothAdmin,
Manifest.Permission.AccessCoarseLocation,
Manifest.Permission.AccessFineLocation
};
protected override void OnCreate(Bundle savedInstanceState)
{
...
CheckPermissions();
LoadApplication(new App());
}
private void CheckPermissions()
{
bool minimumPermissionsGranted = true;
foreach (string permission in Permissions)
{
if (CheckSelfPermission(permission) != Permission.Granted)
{
minimumPermissionsGranted = false;
}
}
// If any of the minimum permissions aren't granted, we request them from the user
if (!minimumPermissionsGranted)
{
RequestPermissions(Permissions, 0);
}
}