iphone - 当 iOS 应用程序进入后台时,长时间的任务是否会暂停?

标签 iphone multitasking

是的,我知道如果我希望我的应用程序能够响应用户的多任务操作(例如切换到另一个应用程序),我应该处理

- (void)applicationWillResignActive:(UIApplication *)application
- (void)applicationDidBecomeActive:(UIApplication *)application

如果我的应用程序正在执行相当长的耗时操作(例如下载大文件)并且用户导致我的应用程序进入后台怎么办?当用户返回我的应用程序时,该操作是否会自动暂停并恢复?

当我的应用进入后台或在前台恢复时,幕后到底会发生什么?

如果当用户让我的应用程序转到后台时,我的应用程序的执行正好在方法的中间怎么办?

例如,我的应用程序正在执行

for (int i = 1 to 10000K) {
    do some calculation;
}

当 i== 500K 时,用户切换到另一个应用程序。我的应用程序中的 for 循环会发生什么情况?

最佳答案

来自documentation :

Return from applicationDidEnterBackground(_:) as quickly as possible. Your implementation of this method has approximately five seconds to perform any tasks and return. If the method doesn’t return before time runs out, your app is terminated and purged from memory.

If you need additional time to perform any final tasks, request additional execution time from the system by calling beginBackgroundTask(expirationHandler:). Call beginBackgroundTask(expirationHandler:) as early as possible. Because the system needs time to process your request, there’s a chance that the system might suspend your app before that task assertion is granted. For example, don’t call beginBackgroundTask(expirationHandler:) at the very end of your applicationDidEnterBackground(_:) method and expect your app to continue running.

如果您上面描述的长时间运行的操作在主线程上,并且在您的应用程序转到后台后需要超过 5 秒才能完成,您的应用程序将被终止。主线程将被阻塞,您将没有机会及时从 -applicationDidEnterBackground: 返回。

如果您的任务在后台线程上运行(确实应该如此,如果执行时间很长),则如果应用程序从 -applicationDidEnterBackground: 返回,则该线程似乎已暂停(根据参见 this answer 中的讨论)。当应用程序返回前台时,它将恢复。

但是,在后一种情况下,您仍然应该准备好在后台清理应用程序时随时终止您的应用程序。

关于iphone - 当 iOS 应用程序进入后台时,长时间的任务是否会暂停?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6650717/

相关文章:

c# - 如何让一定数量的线程一直运行

iPhone + CGAffineTransFormRotate(pi/2) + statusBarHidden :YES + presentModalViewController = 20 pixels of white space

iphone - 我应该使用哪个版本的 iOS SDK?

iOS 多任务处理不工作

c - "multitasking"的 Arduino 算法

android - Android 中的 float 视频播放器?

iphone - iOS4.0 iphone应用程序在后台运行时AudioQueueStart失败

iphone - 如何在 XCode 中屏蔽不需要的 "Dead Store"警告?

iphone - iOS 5 JSON 分级别解析

iphone - 使用图像创建图层时内存警告会导致崩溃