在应用程序后台使用蓝牙低功耗技术

5
我正在使用Xamarin构建一款iOS应用程序,使用以下BLE插件:
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实例并在委托中实现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门户中),我只能看到手机的标识符。

据我所知,你不能仅仅保持广播状态。你可以指定为蓝牙中心或蓝牙外设的2种可能模式之一。你应该在plist中指定。 - Yuri S
你尝试过按照描述将后台模式“UIBackgroundModes”添加到pinfo.list中吗? - Yuri S
是的,我已经添加了所有这些。 - Drake
插件说:“通过允许钩子到WhenWillRestoreState来管理iOS后台运行”。你尝试过连接那个钩子吗? - Yuri S
还有问答:问:在iOS后台扫描时,我无法看到设备名称。这是iOS的工作。库无法修复此问题。您应该通过服务UUID进行扫描。 - Yuri S
显示剩余19条评论
2个回答

2

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

编辑以包括Paulw11的评论(这是真实的): 您可以广告服务,但它是以一种只有特定扫描该服务UUID的其他iOS设备才能看到的方式进行广告的。


1
你可以宣传一个服务,但是它是以一种方式进行宣传的,只有另一个正在特定扫描该服务UUID的iOS设备才能看到。 - Paulw11

0

虽然在 iOS 应用程序处于后台时无法广播 BLE 服务的 UUID,但对于任何试图执行类似操作的人来说,应该研究 iBeacon。这是苹果公司的协议,允许 iOS 应用程序在后台执行蓝牙操作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接