gpt4 book ai didi

ios - 在应用程序处于后台时使用蓝牙 LE

转载 作者:可可西里 更新时间:2023-11-01 04:45:01 25 4
gpt4 key购买 nike

我正在使用 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);

唯一的问题是,一旦我将应用程序置于后台,它就会停止广播。并在我再次打开应用程序时再次恢复。

如何让它在后台继续播放?我在这里阅读了文档:

https://developer.apple.com/library/content/documentation/NetworkingInternetWeb/Conceptual/CoreBluetooth_concepts/CoreBluetoothBackgroundProcessingForIOSApps/PerformingTasksWhileYourAppIsInTheBackground.html

它说我必须使用 CBCentralManager 类来获得保存和恢复功能(这样我就可以一直广播 UUID),但我很难翻译这对 Xamarin/C#。

编辑

进一步研究后,我了解到我需要创建一个 CBCentralManager 实例并在委托(delegate)中实现 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(在我正在测试的信标的门户网站中),我只看到手机的标识符。

最佳答案

经过大量研究,我发现这只是一个 iOS 限制 - 当您的应用程序处于后台时,您不能广播 BLE 服务的 UUID。后台工作在 iOS 中非常受限。

编辑以包含 Paulw11 评论(这是真的):您可以宣传一项服务,但其宣传方式只有专门扫描该服务 UUID 的另一台 iOS 设备才能看到。

关于ios - 在应用程序处于后台时使用蓝牙 LE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44662206/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com