应用程序处于后台时使用Bloothtooth LE

时间:2017-06-20 20:13:15

标签: ios xamarin xamarin.ios

我正在使用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(在我正在测试的信标的门户网站中),我只看到手机的标识符

2 个答案:

答案 0 :(得分:2)

经过大量的研究,我发现它只是一个iOS限制 - 当你的应用程序在后台时,你无法广播BLE服务的UUID。背景工作在iOS中非常严格。

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

答案 1 :(得分:0)

虽然您的iOS应用程序在后台时无法广播BLE服务的UUID,但对于任何尝试执行类似操作的人,您应该查看iBeacon。这是Apple的iOS应用程序在后台运行蓝牙功能的协议。