iOS 中屏幕关闭/设备锁定时定时器不运行

2024-03-23

应用程序位于后台,在与 BLE 设备断开连接时会收到回调,之后应用程序必须等待一段时间(1 分钟),然后执行一些代码。如果屏幕打开,即使在后台,应用程序也会按预期运行。但是,如果屏幕关闭,则计时器将无法工作,并且应用程序不会按预期执行。

这是 AppDelegate 中用于在后台启动计时器的代码:

func startTimerWith(timeInterval: TimeInterval) {
    registerBackgroundTask()
    timer = Timer.scheduledTimer(withTimeInterval: timeInterval, repeats: false, block: { (timer) in
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "Time"), object: nil)
        self.endBackgroundTask()
    })
}

func registerBackgroundTask() {
    backgroundTask = UIApplication.shared.beginBackgroundTask(expirationHandler: {
        self.endBackgroundTask()
    })
}

func endBackgroundTask() {
    print("Background task ended.")
    UIApplication.shared.endBackgroundTask(backgroundTask)
    backgroundTask = UIBackgroundTaskInvalid
    timer?.invalidate()
    timer = nil
}

当与 BLE 设备断开连接时,我通过注册后台任务来启动计时器:

func disconnected(_ peripheral: CBPeripheral, with error: Error?) {
    print("DISCONNECTED!!!")
    AppDelegate.sharedApp().startTimerWith(timeInterval: TimeInterval(TIME))
    BLEDeviceHandler.sharedInstance.handleBLEDevice(connectedPeripheral!)
} 

这里有两点至关重要:

  1. 如果应用程序处于后台状态超过时间,计时器将不起作用10分钟。我有一个确切的场景,我必须执行一些操作 后台操作。我发现10分钟后,计时器没有 工作。
  2. 设备锁定时计时器不起作用。一旦设备被锁定,应用程序就会立即暂停。这是为了iOS >= 7.0
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

iOS 中屏幕关闭/设备锁定时定时器不运行 的相关文章

随机推荐