iOS蓝牙后台运行

2020-12-22  本文已影响0人  iOS虞

我们做的是需要连接蓝牙的App,默认情况下当应用进入后台或挂起时,蓝牙任务将会被终止

开启蓝牙后台模式

在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

配置已经完成,运行代码后发现连接蓝牙设备切入到后台几秒后并不会断开了,但是后台时蓝牙发送广播应用就会被唤醒大约10s,这个时间对于我们应用来说不能够处理广播的数据

延长后台时间

在蓝牙接收到数据的方法里调用backgroundRun()

// MARK: 蓝牙返回数据
    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {

        printLog("==========接收到蓝牙返回数据=========")
        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("===========后台任务结束了==========时间: \(endtime - begintime)")
                application.endBackgroundTask(self.backgroundTask)
                self.backgroundTask = .invalid
            })
        }
    }
}

开启后大概可以达到31秒,这个时间足够了处理一些数据了,如果蓝牙一直广播数据,这个时间还会更长

这样就可以了,就是不知道能不能上线,还有会不会出现没有测到的问题,发现个问题如果锁屏也会不处理数据,找了好久没有找到怎么改 ,经过反复的测试发现如果在不插电源线的情况下会不处理数据

上一篇 下一篇

猜你喜欢

热点阅读