蓝牙后台运行
最近开始做一些关于蓝牙的项目,之前也做过连接蓝牙打印机.做一些简单的打印之类的, 这些网上一搜一大把.就不说了. 但是这次项目需要在后台运行, 后台扫描.连接,发送消息等操作,也上网搜索了大量的资料.
https://www.jianshu.com/p/38a4c6451d93
https://www.jianshu.com/p/927ef9d5d2d1
......
功夫不负苦心人,终于完成了
需要注意的地方
1.蓝牙在后台运行需要打开后台模式(Xcode里面配置)
2.官方文档里面在创建蓝牙管理中心的时候, option里面增加恢复标识
//CBCentralManagerOptionRestoreIdentifierKey app中加入状态的保存和恢复功能的方式很简单
//CBCentralManagerOptionShowPowerAlertKey布尔值,表示如果当前蓝牙没打开,是否弹出alert框(已经不管用了. 可以在centralManagerDidUpdateState 这里检测)
self.centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue() options:@{CBCentralManagerOptionRestoreIdentifierKey:kUaesCentralManagerIdentifier,
CBCentralManagerOptionShowPowerAlertKey:@(1)}];
3.复原central和peripheral manager
当应用被系统唤醒,你需要做的第一件事是使用还原id复原central and peripheral manager。如果应用中只有一个central or peripheral manager,并且在应用的整个生命周期中存在,那么就简单了。
如果应用使用多个central or peripheral manager 或如果应用使用的manager不是在app的整个生命周期中存在,那么应用需要知道哪些managers需要复原。在实现application:didFinishLaunchingWithOptions: 这个代理方法时,通过使用参数launchoptions中的键(UIApplicationLaunchOptionsBluetoothCentralsKey or UIApplicationLaunchOptionsBluetoothPeripheralsKey) 可以获得应用在终止时为我们保存的还原id列表。
第一次做的时候一直没有值,
那什么时候有值.
连接成功以后, 点击按钮闪退.(exit(0)), 等带蓝牙外设自动连接,进入APP这时就有值了.. 很关键
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
NSArray *identifiers = launchOptions[UIApplicationLaunchOptionsBluetoothCentralsKey];
for (NSString *identifier in identifiers){
if ([identifier isEqualToString:kUaesCentralManagerIdentifier]) {
//做你的操作
}
return YES;
}
3.在断开设备的代理方法中写上继续扫描, 指定的serviceID
[self.centralManager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:self.serviceID]] options:@{CBCentralManagerScanOptionAllowDuplicatesKey:@(1)}];
最后测试结果
我用A手机当做蓝牙外设., B手机当做蓝牙中心
A与B第一次连接上以后, 发送消息.... 然后B手机退出后台, A手机进程杀死, 关机.(相当于断开设备), 间隔很久, 打开A手机的蓝牙外设, 可以继续发送消息....
(我要的就是这样的效果, 不管多久, 当距离外设很近时, 可以自动连接. 发送消息)
网友评论