使用CoreBluetooth.framework的應用可以在后臺運行。需要在info.plost文件中增加bluetooth-Central和bluetooth-peripheral鍵.
以下介紹iOS(iOS7)在后臺BLE持續連接外圍設備的開發步驟。
步驟簡述
基本步驟是:
創建項目,設置plist
實現delegate方法,判斷藍牙狀態,如成功則掃描指定UUID設備(如不指定UUID,則無法后臺持續連接)
實現delegate方法,當發現指定設備后,連接該設備
實現delegate方法,當連接指定外圍設備成功,編寫定時器,每秒讀取1次RSSI
實現delegate方法,當監聽到失去和外圍設備連接,重新建立連接
實現delegate方法,當讀取到RSSI值,打印出它的值
創建項目,設置plist
創建一個Single View Application即可。
項目引入CoreBlue.framework。
代碼中:
1
import <CoreBluetooth/CoreBluetooth.h>
讓ViewController實現相應的delegate:
1
@interface ViewController () <CBCentralManagerDelegate, CBPeripheralDelegate>
下面就是實現delegate相關方法了。
判斷藍牙狀態
代碼:
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
DLog();
if (central.state == CBCentralManagerStatePoweredOn) {
[self.centralManger scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:@"f3d9"]]
options:nil];
}
}
其中f3d9是我連接到iPad mini2的LightBlue app模擬的BLE外圍設備,你要換成你設備的UUID。
或者不設置具體的UUID:
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
DLog();
if (central.state == CBCentralManagerStatePoweredOn) {
[self.centralManger scanForPeripheralsWithServices:nil
options:nil];
}
}
貌似這樣也可以,但是運行幾分鐘后,會出現類似這樣的報錯:
1
2014-01-02 11:10:40.799 BLEBackgroundMode[6961:60b] CoreBluetooth[WARNING] <CBPeripheral: 0x15d914a0 identifier = 730CF80B-90F6-C55C-3FB5-66326BDA453A, Name = "iPad", state = connecting> is not connected
發現指定設備后連接該設備
代碼:
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
DLog(@"peripheral name %@ id %@ rssi %d", peripheral.name, peripheral.identifier, [RSSI integerValue]);
self.peripheral = peripheral;
[self.centralManger connectPeripheral:peripheral options:nil];
}
這里要注意,將peripheral對象設置給成員變量,保持對這個對象的引用,否則會因為沒有引用計數而被回收。
連接指定外圍設備后啟動讀取RSSI定時器
代碼:
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
DLog();
self.peripheral.delegate = self;
if (!self.timer) {
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(readRSSI)
userInfo:nil
repeats:1.0];
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
}
}
這里創建了定時器(NSTimer),每間隔1秒讀取1次RSSI,如果讀到了就會觸發peripheral的delegate方法,下面會說。
因為這個方法是iOS系統調用的,因此Timer是通過runloop跑在系統線程中的。
失去和外圍設備連接后重建連接
代碼:
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
[self.centralManger connectPeripheral:peripheral options:nil];
}
這個方法是必須實現的,因為我監控到,我的iPhone4S(Central)連接iPad mini2(Peripheral)大約每10秒鐘就會中斷連接,正好觸發這個方法重建連接。
重建連接可能造成數秒后才能讀取到RSSI。
讀取到RSSI值后的操作
代碼:
- (void)peripheralDidUpdateRSSI:(CBPeripheral *)peripheral error:(NSError *)error
{
if (!error) {
NSLog(@"rssi %d", [[peripheral RSSI] integerValue]);
}
}
這個方法讀取到RSSI值,本示例中,基本上每秒讀取到1次。
存在的問題
需要進一步測試,比如跑其他大應用,系統是否會停止BLE連接,這方面是否需要保持狀態。