是的,我知道如果我希望我的应用程序能够响应用户的多任务操作(例如切换到另一个应用程序),我应该处理
- (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:)
. CallbeginBackgroundTask(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 callbeginBackgroundTask(expirationHandler:)
at the very end of yourapplicationDidEnterBackground(_:)
method and expect your app to continue running.
如果您上面描述的长时间运行的操作在主线程上,并且在您的应用程序转到后台后需要超过 5 秒才能完成,您的应用程序将被终止。主线程将被阻塞,您将没有机会及时从 -applicationDidEnterBackground:
返回。
如果您的任务在后台线程上运行(确实应该如此,如果执行时间很长),则如果应用程序从 -applicationDidEnterBackground:
返回,则该线程似乎已暂停(根据参见 this answer 中的讨论)。当应用程序返回前台时,它将恢复。
但是,在后一种情况下,您仍然应该准备好在后台清理应用程序时随时终止您的应用程序。
关于iphone - 当 iOS 应用程序进入后台时,长时间的任务是否会暂停?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6650717/