123456789101112131415161718192021222324252627282930313233343536373839404142434445464748 |
- import UIKit
- import Flutter
- @UIApplicationMain
- @objc class AppDelegate: FlutterAppDelegate{
-
- var bgTask: UIBackgroundTaskIdentifier!
-
- override func application(
- _ application: UIApplication,
- didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
- ) -> Bool {
- GeneratedPluginRegistrant.register(with: self)
- return super.application(application, didFinishLaunchingWithOptions: launchOptions)
- }
-
- //app进入后台
- override func applicationDidEnterBackground(_ application: UIApplication){
- //开启后台任务保活
- comeToBackgroundMode()
- }
-
- func comeToBackgroundMode() {
- //初始化一个后台任务BackgroundTask,这个后台任务的作用就是告诉系统当前app在后台有任务处理,需要时间
- let app = UIApplication.shared
- bgTask = app.beginBackgroundTask(expirationHandler: { [self] in
- app.endBackgroundTask(bgTask)
- bgTask = UIBackgroundTaskIdentifier.invalid
- })
- //开启定时器 不断向系统请求后台任务执行的时间
- let timer = Timer.scheduledTimer(timeInterval: 30.0, target: self, selector: #selector(applyForMoreTime), userInfo: nil, repeats: true)
- timer.fire()
- }
- @objc func applyForMoreTime() {
- //如果系统给的剩余时间小于60秒 就终止当前的后台任务,再重新初始化一个后台任务,重新让系统分配时间,这样一直循环下去,保持APP在后台一直处于active状态。
- if UIApplication.shared.backgroundTimeRemaining < 60 {
- UIApplication.shared.endBackgroundTask(bgTask)
- bgTask = UIApplication.shared.beginBackgroundTask(expirationHandler: { [self] in
- UIApplication.shared.endBackgroundTask(bgTask)
- bgTask = UIBackgroundTaskIdentifier.invalid
- })
- }
- }
-
- }
|