藍牙后臺運行
最近開始做一些關于藍牙的項目,之前也做過連接藍牙打印機.做一些簡單的打印之類的, 這些網(wǎng)上一搜一大把.就不說了. 但是這次項目需要在后臺運行, 后臺掃描.連接,發(fā)送消息等操作,也上網(wǎng)搜索了大量的資料.
http://www.itdecent.cn/p/38a4c6451d93
http://www.itdecent.cn/p/927ef9d5d2d1
......
功夫不負苦心人,終于完成了
需要注意的地方
1.藍牙在后臺運行需要打開后臺模式(Xcode里面配置)
2.官方文檔里面在創(chuàng)建藍牙管理中心的時候, option里面增加恢復標識
//CBCentralManagerOptionRestoreIdentifierKey app中加入狀態(tài)的保存和恢復功能的方式很簡單
//CBCentralManagerOptionShowPowerAlertKey布爾值,表示如果當前藍牙沒打開,是否彈出alert框(已經不管用了. 可以在centralManagerDidUpdateState 這里檢測)
self.centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue() options:@{CBCentralManagerOptionRestoreIdentifierKey:kUaesCentralManagerIdentifier,
CBCentralManagerOptionShowPowerAlertKey:@(1)}];
3.復原central和peripheral manager
當應用被系統(tǒng)喚醒,你需要做的第一件事是使用還原id復原central and peripheral manager。如果應用中只有一個central or peripheral manager,并且在應用的整個生命周期中存在,那么就簡單了。
如果應用使用多個central or peripheral manager 或如果應用使用的manager不是在app的整個生命周期中存在,那么應用需要知道哪些managers需要復原。在實現(xiàn)application:didFinishLaunchingWithOptions: 這個代理方法時,通過使用參數(shù)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.在斷開設備的代理方法中寫上繼續(xù)掃描, 指定的serviceID
[self.centralManager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:self.serviceID]] options:@{CBCentralManagerScanOptionAllowDuplicatesKey:@(1)}];
最后測試結果
我用A手機當做藍牙外設., B手機當做藍牙中心
A與B第一次連接上以后, 發(fā)送消息.... 然后B手機退出后臺, A手機進程殺死, 關機.(相當于斷開設備), 間隔很久, 打開A手機的藍牙外設, 可以繼續(xù)發(fā)送消息....
(我要的就是這樣的效果, 不管多久, 當距離外設很近時, 可以自動連接. 發(fā)送消息)