- // 1.点击home
- // 2.锁屏
- - (void) applicationDidEnterBackground: (UIApplication * ) application {
- NSLog(@"app didEnterBackground");
- //start background task
- __block UIBackgroundTaskIdentifier background_task;
- //background task running time differs on different iOS versions.
- //about 10 mins on early iOS, but only 3 mins on iOS7.
- background_task = [application beginBackgroundTaskWithExpirationHandler: ^{
- NSLog(@"task expired..."); [application endBackgroundTask: background_task];
- background_task = UIBackgroundTaskInvalid;
- }];
- dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
- while (true) {
- float remainingTime = [application backgroundTimeRemaining];
- NSLog(@"remaining background time:%f", remainingTime); [NSThread sleepForTimeInterval: 1.0];
- __block BOOL inForeground = false;
- dispatch_sync(dispatch_get_main_queue(), ^{
- inForeground = ([UIApplication sharedApplication].applicationState == UIApplicationStateActive);
- });
- if (remainingTime <= 3.0 || inForeground) {
- NSLog(@"endBackgroundTask");
- break;
- }
- } [application endBackgroundTask: background_task];
- background_task = UIBackgroundTaskInvalid;
- });
- }
来源: http://lib.csdn.net/snippet/ios/42289