用户按下主屏幕按钮将调用applicationWillResignActive:,如果谈们稍后将应用切换回前台,将调用applicationDidBecomeActive:。如果用户接听电话,也会发生相同序列的事件。最神奇的是应用启动时也会调用applicationDidBecomeActive:。这两个方法可以用来启动或禁用任何动画、应用内的音频或者其他用于向用户展示的应用内元素。由于使用applicationDidBecomeActive:较多,我们可能在其中添加一些应用初始化代码,而不是在application:didFinishLaunchingWithOptions:中。
当设备显示收到信息的提醒时,将调用applicationWillResignActive:,应用没有被发送到后台,而是出于不活跃状态,如果此应用是一个游戏或正在进行着视频、音频或动画,那么这是需要暂停他们。点击关闭按钮将调用applicationDidBecomeActive:,点击回复按钮将依次调用applicationDidBecomeActive:、applicationWillResignActive:和applicationDidEnterBackground:三个方法。
applicationDidEnterBackground:中释放所有可在以后重新创建的资源,保存所用用户数据,关闭网络连接等。如果需要还可以在这里请求在后台运行更长的时间用来保存数据。
applicationWillEnterForeground:中重新创建在applicationDidEnterBackground:中销毁的内容,比如重新加载用户数据、重新建立网络连接等。
1 #import "BIDViewController.h" 2 3 @interface BIDViewController () 4 5 @property (strong, nonatomic) UILabel * label; 6 @property (strong, nonatomic) UIImage * smiley; 7 @property (strong, nonatomic) UIImageView * smileyView; 8 @property (strong, nonatomic) UISegmentedControl * segmentedControl; 9 10 @end 11 12 @implementation BIDViewController 13 { 14 BOOL animate; 15 } 16 17 - (void)viewDidLoad 18 { 19 [super viewDidLoad]; 20 21 //创建Label 22 CGRect bounds = self.view.bounds; 23 CGRect labelFrame = CGRectMake(bounds.origin.x, CGRectGetMidY(bounds) - 50, 24 bounds.size.width, 100); 25 self.label = [[UILabel alloc] initWithFrame:labelFrame]; 26 self.label.font = [UIFont fontWithName:@"Helvetica" size:70]; 27 self.label.text = @"Bazinga!"; 28 self.label.textAlignment = NSTextAlignmentCenter; 29 self.label.backgroundColor = [UIColor clearColor]; 30 31 // 创建ImageView, smiley.png is 84 x 84 32 CGRect smileyFrame = CGRectMake(CGRectGetMidX(bounds) - 42, 33 CGRectGetMidY(bounds)/2 - 42, 34 84, 84); 35 self.smileyView = [[UIImageView alloc] initWithFrame:smileyFrame]; 36 self.smileyView.contentMode = UIViewContentModeCenter; 37 NSString *smileyPath = [[NSBundle mainBundle] pathForResource:@"smiley" 38 ofType:@"png"]; 39 self.smiley = [UIImage imageWithContentsOfFile:smileyPath]; 40 self.smileyView.image = self.smiley; 41 42 43 //在哪里恢复分段选择的索引并用于配置分段控件,applicationWillEnterForeground方法并不是我们想要的。这个方法被调用的时候应用已经处于运行状态,但设置还是最原始的状态。应该在应用重新运行之后就进行设置,应该在viewDidLoad方法中进行处理。 44 self.segmentedControl = [[UISegmentedControl alloc] initWithItems: 45 [NSArray arrayWithObjects: 46 @"One", @"Two", @"Three", @"Four", nil]] ; 47 self.segmentedControl.frame = CGRectMake(bounds.origin.x + 20, 48 50, 49 bounds.size.width - 40, 30); 50 51 52 [self.view addSubview:self.segmentedControl]; 53 [self.view addSubview:self.smileyView]; 54 [self.view addSubview:self.label]; 55 56 NSNumber *indexNumber = [[NSUserDefaults standardUserDefaults] 57 objectForKey:@"selectedIndex"]; 58 if (indexNumber) { 59 NSInteger selectedIndex = [indexNumber intValue]; 60 self.segmentedControl.selectedSegmentIndex = selectedIndex; 61 } 62 63 NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; 64 [center addObserver:self 65 selector:@selector(applicationWillResignActive) 66 name:UIApplicationWillResignActiveNotification 67 object:nil]; 68 [center addObserver:self 69 selector:@selector(applicationDidBecomeActive) 70 name:UIApplicationDidBecomeActiveNotification 71 object:nil]; 72 73 [center addObserver:self 74 selector:@selector(applicationDidEnterBackground) 75 name:UIApplicationDidEnterBackgroundNotification 76 object:nil]; 77 [center addObserver:self 78 selector:@selector(applicationWillEnterForeground) 79 name:UIApplicationWillEnterForegroundNotification 80 object:nil]; 81 } 82 83 - (void)rotateLabelDown 84 { 85 [UIView animateWithDuration:0.5 86 animations:^{ 87 self.label.transform = CGAffineTransformMakeRotation(M_PI); 88 } 89 completion:^(BOOL finished){ 90 [self rotateLabelUp]; 91 }]; 92 } 93 94 - (void)rotateLabelUp 95 { 96 [UIView animateWithDuration:0.5 97 animations:^{ 98 self.label.transform = CGAffineTransformMakeRotation(0); 99 } 100 completion:^(BOOL finished){ 101 if (animate) { 102 [self rotateLabelDown]; 103 } 104 }]; 105 } 106 107 - (void)applicationWillResignActive 108 { 109 NSLog(@"VC: %@", NSStringFromSelector(_cmd)); 110 animate = NO; 111 } 112 113 - (void)applicationDidBecomeActive 114 { 115 NSLog(@"VC: %@", NSStringFromSelector(_cmd)); 116 animate = YES; 117 [self rotateLabelDown]; 118 } 119 120 - (void)applicationDidEnterBackground 121 { 122 NSLog(@"VC: %@", NSStringFromSelector(_cmd)); 123 UIApplication *app = [UIApplication sharedApplication]; 124 125 __block UIBackgroundTaskIdentifier taskId; 126 taskId = [app beginBackgroundTaskWithExpirationHandler:^{ 127 NSLog(@"Background task ran out of time and was terminated."); 128 [app endBackgroundTask:taskId]; 129 }]; 130 131 if (taskId == UIBackgroundTaskInvalid) { 132 NSLog(@"Failed to start background task!"); 133 return; 134 } 135 136 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), 137 ^{ 138 NSLog(@"Starting background task with %f seconds remaining", 139 app.backgroundTimeRemaining); 140 141 self.smiley = nil; 142 self.smileyView.image = nil; 143 NSInteger selectedIndex = self.segmentedControl.selectedSegmentIndex; 144 [[NSUserDefaults standardUserDefaults] setInteger:selectedIndex 145 forKey:@"selectedIndex"]; 146 147 // simulate a lengthy (25 seconds) procedure 148 [NSThread sleepForTimeInterval:25]; 149 150 NSLog(@"Finishing background task with %f seconds remaining", 151 app.backgroundTimeRemaining); 152 [app endBackgroundTask:taskId]; 153 }); 154 } 155 156 - (void)applicationWillEnterForeground 157 { 158 NSLog(@"VC: %@", NSStringFromSelector(_cmd)); 159 NSString * smileyPath = [[NSBundle mainBundle] pathForResource:@"smiley" 160 ofType:@"png"]; 161 self.smiley = [UIImage imageWithContentsOfFile:smileyPath]; 162 self.smileyView.image = self.smiley; 163 } 164 165 - (void)didReceiveMemoryWarning 166 { 167 [super didReceiveMemoryWarning]; 168 // Dispose of any resources that can be recreated. 169 }