我們做的是需要連接藍(lán)牙的App,默認(rèn)情況下當(dāng)應(yīng)用進(jìn)入后臺(tái)或掛起時(shí)沮焕,藍(lán)牙任務(wù)將會(huì)被終止
開啟藍(lán)牙后臺(tái)模式
在Xcode中配置 TARGET
-> Signig & Capabilities
-> Capabitity
在搜索框中輸入Background Modes
找到后臺(tái)添加荞驴,并勾選Uses Bluetooth LE accessories
, Acts as a Bluetooth LE accessory
, Background processing
配置已經(jīng)完成策治,運(yùn)行代碼后發(fā)現(xiàn)連接藍(lán)牙設(shè)備切入到后臺(tái)幾秒后并不會(huì)斷開了拐云,但是后臺(tái)時(shí)藍(lán)牙發(fā)送廣播應(yīng)用就會(huì)被喚醒大約10s田炭,這個(gè)時(shí)間對(duì)于我們應(yīng)用來說不能夠處理廣播的數(shù)據(jù)
延長(zhǎng)后臺(tái)時(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("===========后臺(tái)任務(wù)結(jié)束了==========時(shí)間: \(endtime - begintime)")
application.endBackgroundTask(self.backgroundTask)
self.backgroundTask = .invalid
})
}
}
}
開啟后大概可以達(dá)到31秒查吊,這個(gè)時(shí)間足夠了處理一些數(shù)據(jù)了谐区,如果藍(lán)牙一直廣播數(shù)據(jù),這個(gè)時(shí)間還會(huì)更長(zhǎng)
這樣就可以了逻卖,就是不知道能不能上線宋列,還有會(huì)不會(huì)出現(xiàn)沒有測(cè)到的問題,發(fā)現(xiàn)個(gè)問題如果鎖屏也會(huì)不處理數(shù)據(jù),找了好久沒有找到怎么改 ,經(jīng)過反復(fù)的測(cè)試發(fā)現(xiàn)如果在不插電源線的情況下會(huì)不處理數(shù)據(jù)