轉自:http://sis hu ok.com/forum/blogCategory/showByCategory.html?categories_id=138&user_id=10385
居然話sis hu ok.com違禁 嗨~~~ 想看原文請把空格去掉
// 當應用程序掉到后台時,執行該方法
- (void)applicationDidEnterBackground:(UIApplication *)application
{
}
當一個 iOS 應用被送到后台,它的主線程會被暫停。你用 NSThread 的 detachNewThreadSelector:toTar get:withObject:類方法創建的線程也被掛起了。
1.我們需要在應用程序推到后台時,能夠有足夠的時間來完成將數據保存到遠程服務器的操作。
2.有足夠的時間記錄一些需要的信息操作。
當一個 iOS 應用被送到后台,它的主線程會被暫停。你用 NSThread 的 detachNewThreadSelector:toTar get:withObject:類方法創建的線程也被掛起了。
如果你想在后台完成一個長期任務,就必須調用 UIApplication 的 beginBackgroundTaskWithExpirationHandler:實例方法,來向 iOS 借點時間。
默認情況下,如果在這個期限內,長期任務沒有被完成,iOS 將終止程序。
怎么辦?可以使用 beginBackgroundTaskWithExpirationHandler:實例方法,來向 iOS 再借點時間。
@property (nonatomic, unsafe_unretained) UIBackgroundTaskIdentifier backgroundTaskIdentifier;
@property (nonatomic, strong) NSTimer *myTimer;
[self endBackgroundTask];
}];
// 當應用程序掉到后台時,執行該方法
// 當一個 iOS 應用被送到后台,它的主線程會被暫停。你用 NSThread 的 detachNewThreadSelector:toTar get:withObject:類方法創建的線程也被掛起了。
// 如果你想在后台完成一個長期任務,就必須調用 UIApplication 的 beginBackgroundTaskWithExpirationHandler:實例方法,來向 iOS 借點時間。
// 默認情況下,如果在這個期限內,長期任務沒有被完成,iOS 將終止程序。
// 怎么辦?可以使用 beginBackgroundTaskWithExpirationHandler:實例方法,來向 iOS 再借點時間。
- (void)applicationDidEnterBackground:(UIApplication *)application
{
// 使用這個方法來釋放公共的資源、存儲用戶數據、停止我們定義的定時器(timers)、並且存儲在程序終止前的相關信息。
// 如果,我們的應用程序提供了后台執行的方法,那么,在程序退出時,這個方法將代替applicationWillTerminate方法的執行。
// 標記一個長時間運行的后台任務將開始
// 通過調試,發現,iOS給了我們額外的10分鍾(600s)來執行這個任務。
self.backgroundTaskIdentifier =[application beginBackgroundTaskWithExpirationHandler:^(void) {
// 當應用程序留給后台的時間快要到結束時(應用程序留給后台執行的時間是有限的), 這個Block塊將被執行
// 我們需要在次Block塊中執行一些清理工作。
// 如果清理工作失敗了,那么將導致程序掛掉
// 清理工作需要在主線程中用同步的方式來進行
[self endBackgroundTask];
}];
// 模擬一個Long-Running Task
self.myTimer =[NSTimer scheduledTimerWithTimeInterval:1.0f
target:self
selector:@selector(timerMethod:) userInfo:nil
repeats:YES];
}
[[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskIdentifier];
strongSelf.backgroundTaskIdentifier = UIBackgroundTaskInvalid;
}
});
- (void) endBackgroundTask{
dispatch_queue_t mainQueue = dispatch_get_main_queue();
AppDelegate *weakSelf = self;
dispatch_async(mainQueue, ^(void) {
AppDelegate *strongSelf = weakSelf;
if (strongSelf != nil){
[strongSelf.myTimer invalidate];// 停止定時器
// 每個對 beginBackgroundTaskWithExpirationHandler:方法的調用,必須要相應的調用 endBackgroundTask:方法。這樣,來告訴應用程序你已經執行完成了。
// 也就是說,我們向 iOS 要更多時間來完成一個任務,那么我們必須告訴 iOS 你什么時候能完成那個任務。
// 也就是要告訴應用程序:“好借好還”嘛。
// 標記指定的后台任務完成
[[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskIdentifier];
// 銷毀后台任務標識符
strongSelf.backgroundTaskIdentifier = UIBackgroundTaskInvalid;
}
});
}
// 模擬的一個 Long-Running Task 方法
- (void) timerMethod:(NSTimer *)paramSender{
// backgroundTimeRemaining 屬性包含了程序留給的我們的時間
NSTimeInterval backgroundTimeRemaining =[[UIApplication sharedApplication] backgroundTimeRemaining];
if (backgroundTimeRemaining == DBL_MAX){
NSLog(@"Background Time Remaining = Undetermined");
} else {
NSLog(@"Background Time Remaining = %.02f Seconds", backgroundTimeRemaining);
}
}
[[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskIdentifier];
self.backgroundTaskIdentifier = UIBackgroundTaskInvalid;
- (void)viewDidLoad
{
[super viewDidLoad];
dispatch_queue_t dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(dispatchQueue, ^(void) {
NSError *audioSessionError = nil;
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
if ([audioSession setCategory:AVAudioSessionCategoryPlayback error:&audioSessionError]){
NSLog(@"Successfully set the audio session.");
} else {
NSLog(@"Could not set the audio session");
}
NSBundle *mainBundle = [NSBundle mainBundle];
NSString *filePath = [mainBundle pathForResource:@"mySong" ofType:@"mp3"];
NSData *fileData = [NSData dataWithContentsOfFile:filePath];
NSError *error = nil;
self.audioPlayer = [[AVAudioPlayer alloc] initWithData:fileData error:&error];
if (self.audioPlayer != nil){
self.audioPlayer.delegate = self;
[self.audioPlayer setNumberOfLoops:-1];
if ([self.audioPlayer prepareToPlay] && [self.audioPlayer play]){
NSLog(@"Successfully started playing...");
} else {
NSLog(@"Failed to play.");
}
} else {
}
});
}