我正在使用Xamarin使用此BLE插件构建iOS应用:
https://github.com/aritchie/bluetoothle
我只是通过BLE广播UUID,并且它可以正常工作。这是我的代码:
var data = new Plugin.BluetoothLE.Server.AdvertisementData
{
LocalName = "MyServer",
};
data.ServiceUuids.Add(new Guid("MY_UUID_HERE"));
await this.server.Start(data);
唯一的问题是,一旦我将应用置于后台,它就会停止广播。并在我再次打开应用程序时再次恢复。
一旦它进入后台,我如何让它继续广播?我在这里阅读文档:
它说我必须使用CBCentralManager
该类来获取保留和恢复功能(这样我就可以一直广播UUID),但是我很难将其转换为Xamarin / C#。
编辑
在研究了更多内容之后,我读到我需要创建一个实例CBCentralManager
并WillRestoreState
在委托中实现。我在AppDelegate
:
[Register("AppDelegate")]
public class AppDelegate : MvxApplicationDelegate, ICBCentralManagerDelegate
{
private IGattServer server = CrossBleAdapter.Current.CreateGattServer();
private CBCentralManager cbCentralManager;
public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
{
// irrelevant code...
this.Ble();
return true;
}
private async Task Ble()
{
try
{
await Task.Delay(5000); // wait for it to finish initializing so I can access BLE (it crashes otherwise)
var options = new CBCentralInitOptions();
options.RestoreIdentifier = "myRestoreIndentifier";
this.cbCentralManager = new CBCentralManager(this,null,options);
var data = new Plugin.BluetoothLE.Server.AdvertisementData
{
LocalName = "MyServer",
};
data.ServiceUuids.Add(new Guid("MY_UUID_HERE"));
await this.server.Start(data);
}
catch (Exception e)
{
}
}
public void UpdatedState(CBCentralManager central)
{
//throw new NotImplementedException();
}
[Export("centralManager:willRestoreState:")]
public void WillRestoreState(CBCentralManager central, NSDictionary dict)
{
//never gets called
}
但这对我没有影响。而且该WillRestoreState
方法永远不会被调用...如果需要,我现在不介意使用其他插件/库...
编辑2
我只是意识到该应用程序在后台时仍在广播,只是不再看到服务UUID(在我正在测试的信标的Web门户中),我只看到了手机的标识符。
经过大量研究后,我发现这仅仅是iOS的限制-当您的应用程序在后台运行时,您无法广播BLE服务的UUID。在iOS中,后台工作非常严格。
编辑以包含Paulw11注释(这是对的)(可以):您可以播发服务,但是播发的方式是只有另一个专门扫描该UUID服务的iOS设备才能看到。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句