在CoreBluetooth Framework中从未见过关于在后台保持连接活动的任何内容

时间:2014-02-13 09:11:00

标签: iphone ios7 background-process bluetooth-lowenergy core-bluetooth

我正在使用Xcode 5和CoreBluetooth框架 在plist文件中

所需的背景模式 - >应用程序使用CoreBluetooth进行通信

在Xcode 5中是应用程序功能中背景模式的部分。将背景模式设为并检查“使用蓝牙LE配件”

我们的应用和BLE连接在应用运行时运行良好 问题是当手机进入睡眠状态或背部进入后台时,BLE连接会停止工作 我还没有在CoreBluetooth框架中看到任何关于在后台保持连接活动的内容。

当app获得背景而不是将方法调用到 startBackgroundNotification 。如下方法

-(void)startBackgroundNotification{
    self.counterTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
            [[UIApplication sharedApplication] endBackgroundTask:counterTask];
    }];
    BackgroundManager = [[CBCentralManager alloc]initWithDelegate:self queue:nil];
    nDevices = [[NSMutableArray alloc]init];
    sensorTags = [[NSMutableArray alloc]init];
}

在startBackgroundNotification调用之后调用(委托)到 centralManagerDidUpdateState

-(void)centralManagerDidUpdateState:(CBCentralManager *)central {
    if (central.state != CBCentralManagerStatePoweredOn) {
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"BLE not supported !"
                                                               message:[NSString stringWithFormat:@"CoreBluetooth return state: %d",central.state]
                                                              delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alertView show];
        }
    }
    else
        [central scanForPeripheralsWithServices:nil options:nil];
}

但永远不要调用以下功能

-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{
}


当应用程序在后台并且我们按下BLE设备上的按钮时,手机会发出通知,说明设备需要访问应用程序,因此我必须再次手动打开应用程序。

1 个答案:

答案 0 :(得分:1)

这实际上记录在Apple的API文档中;在没有扫描任何服务的情况下进行扫描不会在后台返回任何内容,如here所述:

  

指定蓝牙中央背景模式的应用程序可以在后台扫描。也就是说,他们必须通过在serviceUUIDs参数中指定它们来显式扫描一个或多个服务。在后台扫描时,将忽略CBCentralManagerOptionShowPowerAlertKey扫描选项。

因此,要获得任何结果,您必须通过在serviceUUIDs参数中传递UUID来扫描具有特定服务的外围设备。或者,如果您已连接到之前正在寻找的设备,则可以直接拨打connectPeripheral功能