AppDelegate中的几个方法,主要涉及APP启动和前后台切换的一些状态改变,而在这变化中响应方法的执行顺序是怎样的,在这篇文章中做一个小的总结。
首先要了解app的基本状态:
image.png- not running:app还没有运行
- inactive:app运行在前台但是没有接收事件
- active:app运行在前台并且正在接受事件
- background:app运行在后台且在执行代码
- suspended:app运行在后台但已并不执行代码
其次是AppDelegate中的方法:
//启动程序后第一次有机会来执行代码
- (BOOL)application:(UIApplication *)application willFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSLog(@"willFinishLaunching");
return YES;
}
//在app展示给用户前指定的最后初始化方法
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//在程序启动后,配置自定义设置的位置,这里关系到app的启动时间问题,如果不是必须要在一开始启动就初始化的东西,尽量不要放在这里来处理
NSLog(@"didFinishLaunching");
return YES;
}
//app将从前台切换到后台时需要执行的操作
- (void)applicationWillResignActive:(UIApplication *)application {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
// 应用即将从活动状态切换到不活动状态会触发这个方法,在出现某种临时中断(比如来电或者短信)或者用户退出应用程序时都会触发这个方法,然后应用就会转换为后台运行。可以在这个方法中暂停正在进行的任务,禁用定时器,降低opengles帧率。如果是游戏应用,应该在方法中暂停游戏。
NSLog(@"willResignActive");
}
//app已经进入后台时需要执行的操作
- (void)applicationDidEnterBackground:(UIApplication *)application {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
// 在该方法中释放共享资源,保存用户数据,清除定时器。并存储足够的应用状态信息,目的是当应用终止时,将它恢复到当前状态。如果你的应用支持在后台运行,那么当用户退出时调用这个方法而不是applicationwillterminater:方法
NSLog(@"didEnterBackground");
}
//app将要从后台切换到前台需要执行的操作,但app还不是active状态
- (void)applicationWillEnterForeground:(UIApplication *)application {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
//这个方法会在应用程序从后台专到前台过程中被调用,可以在这边恢复正常运行所需要的信息。
NSLog(@"willEnterForeground");
}
//app已经切换到active状态后需要执行的操作
- (void)applicationDidBecomeActive:(UIApplication *)application {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
NSLog(@"didBecomeActive");
}
//app将要结束时需要执行的操作
- (void)applicationWillTerminate:(UIApplication *)application {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// 程序即将终止时调用此方法,如果有必要可以保存数据
NSLog(@"willTerminate");
}
App状态改变时方法的调用顺序:
1、App启动时
image.png2、App进入后台时
image.png3、App从后台返回前台时
image.png
网友评论