我們做的是需要連接藍(lán)牙的App,默認(rèn)情況下當(dāng)應(yīng)用進(jìn)入后臺或掛起時(shí),藍(lán)牙任務(wù)將會被終止
開啟藍(lán)牙后臺模式
在Xcode中配置 TARGET -> Signig & Capabilities -> Capabitity

QQ20201222-115906.png
在搜索框中輸入Background Modes 找到后臺添加,并勾選Uses Bluetooth LE accessories, Acts as a Bluetooth LE accessory, Background processing

QQ20201222-120345.png
配置已經(jīng)完成,運(yùn)行代碼后發(fā)現(xiàn)連接藍(lán)牙設(shè)備切入到后臺幾秒后并不會斷開了,但是后臺時(shí)藍(lán)牙發(fā)送廣播應(yīng)用就會被喚醒大約10s,這個(gè)時(shí)間對于我們應(yīng)用來說不能夠處理廣播的數(shù)據(jù)
延長后臺時(shí)間
在藍(lán)牙接收到數(shù)據(jù)的方法里調(diào)用backgroundRun()
// MARK: 藍(lán)牙返回?cái)?shù)據(jù)
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
printLog("==========接收到藍(lán)牙返回?cái)?shù)據(jù)=========")
let application = UIApplication.shared
if application.applicationState == .background {
let appdelegate = application.delegate as! AppDelegate
appdelegate.backgroundRun()
}
BaseBlueTooth.didUpdateValue?(peripheral, characteristic)
}
//
// AppDelegate.swift
// SugarTools
//
// Created by wujiu on 2020/7/16.
// Copyright ? 2020 yzk. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
fileprivate var backgroundTask = UIBackgroundTaskIdentifier.invalid
func applicationWillEnterForeground(_ application: UIApplication) {
backgroundTask = .invalid
application.endBackgroundTask(backgroundTask)
}
func backgroundRun() {
let application = UIApplication.shared
if backgroundTask == .invalid {
let begintime = CFAbsoluteTimeGetCurrent()
backgroundTask = application.beginBackgroundTask(expirationHandler: {
let endtime = CFAbsoluteTimeGetCurrent()
printLog("===========后臺任務(wù)結(jié)束了==========時(shí)間: \(endtime - begintime)")
application.endBackgroundTask(self.backgroundTask)
self.backgroundTask = .invalid
})
}
}
}
開啟后大概可以達(dá)到31秒,這個(gè)時(shí)間足夠了處理一些數(shù)據(jù)了,如果藍(lán)牙一直廣播數(shù)據(jù),這個(gè)時(shí)間還會更長
這樣就可以了,就是不知道能不能上線,還有會不會出現(xiàn)沒有測到的問題,發(fā)現(xiàn)個(gè)問題如果鎖屏也會不處理數(shù)據(jù),找了好久沒有找到怎么改 ,經(jīng)過反復(fù)的測試發(fā)現(xiàn)如果在不插電源線的情況下會不處理數(shù)據(jù)