IOS允許長時間在后臺運行的情況有7種:
audio
VoIP
GPS
下載新聞
和其它附屬硬件進行通訊時
使用藍牙進行通訊時
使用藍牙共享數據時
除以上情況,程序退出時可能設置短暫運行10分鐘
讓程序退出后臺時繼續運行10分鐘
在XXAppDelegate中增加:UIBackgroundTaskIdentifier bgTask;
- (void)applicationDidEnterBackground:(UIApplication *)application{
bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
// 10分鐘后執行這里,應該進行一些清理工作,如斷開和服務器的連接等
// ...
// stopped or ending the task outright.
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
if (bgTask == UIBackgroundTaskInvalid) {
NSLog(@"failed to start background task!");
}
// Start the long-running task and return immediately.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Do the work associated with the task, preferably in chunks.
NSTimeInterval timeRemain = 0;
do{
[NSThread sleepForTimeInterval:5];
if (bgTask!= UIBackgroundTaskInvalid) {
timeRemain = [application backgroundTimeRemaining];
NSLog(@"Time remaining: %f",timeRemain);
}
}while(bgTask!= UIBackgroundTaskInvalid && timeRemain > 0);
// 如果改為timeRemain > 5*60,表示后臺運行5分鐘
// done!
// 如果沒到10分鐘,也可以主動關閉后臺任務,但這需要在主線程中執行,否則會出錯
dispatch_async(dispatch_get_main_queue(), ^{
if (bgTask != UIBackgroundTaskInvalid){
// 和上面10分鐘后執行的代碼一樣
// ...
// if you don't call endBackgroundTask, the OS will exit your app.
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}
});
});
}
- (void)applicationWillEnterForeground:(UIApplication *)application{
// 如果沒到10分鐘又打開了app,結束后臺任務
if (bgTask!=UIBackgroundTaskInvalid) {
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}
}
?
后臺時,如果某些代碼你不希望執行,可以加以下條件:
UIApplication *application = [UIApplication sharedApplication];
if( application.applicationState == UIApplicationStateBackground) {
return;
}
?有的app雖然我們不允許通知,但還是會彈出消息,應該是設置了定時器,到某一時間就讓程序后臺運行一會,從服務器更新數據,然后顯示出來。