首先文章介绍了由于嵌入式硬件资源的有限,就需要对APP的状态进行特别的管理。
APP在整个运行周期内分成前台运行和后台运行两种,再细分一下一共有如下5中状态:
not running | APP未启动 |
inactive | 虽然在前端运行但是不相应任何用户输入。 |
active | APP正常运行 |
background | 在suspend之前的一种缓冲状态,可以运行代码 |
suspended | 在后台但是不会运行代码,内存会被暂时保存,但是如果系统内存不够将会被清理出去。 |
细看上面的图我们知道,APP不可能直接从active转化带background,之间还要经过一个inactive的状态,inactive和active同属于前端运行,这个图包括了很多的信息,值得去认真看。
对应到这些状态的的API如下:
-
application:willFinishLaunchingWithOptions:
—app的代码第一次被加载. -
application:didFinishLaunchingWithOptions:
—呈现给用户之前最后的初始化. -
applicationDidBecomeActive:
—程序即将进入 foreground 的状态. Use this method for any last minute preparation. -
applicationWillResignActive:
—程序即将离开前台 -
applicationDidEnterBackground:
—程序已经进入了background,且随时有可能被suspended -
applicationWillEnterForeground:
—程序即将离开background到foreground. -
applicationWillTerminate:
—程序即将终止.如果程序已经suspended这个函数将不会被调用.
程序前端的运行状态图
程序在后台的运行状态图
上面两个图的lanch相同,不同的只是下面的event loop的框,至于怎么判断程序在即将在前台还是后台运行,通过application:willFinishLaunchingWithOptions:
or application:didFinishLaunchingWithOptions
查看applicationState(
UIApplication的shared instance
)的状态是UIApplicationStateInactive还是UIApplicationStateBackground。
中断相应流程
前后端的转化流程
applicationDidEnterBackground:
这个函数很特别他只有 5 秒的运行时间否则程序会直接被kill. 所以你只有5秒去保存临时数据, 如果实在不行就调用beginBackgroundTaskWithExpirationHandler
启动后台进程。
返回前端