IOS 後臺掛起程式 當程式到後臺後,繼續完成Long Running Task 任務

weixin_34393428發表於2017-12-13

IOS 後臺掛起程式 當程式到後臺後,繼續完成Long-Running Task 任務 www.douban.com/note/375127… http://lqzit.iteye.com/blog/2068741

github上寫了一個簡單dome的通過後臺位置更新保證app不被kill https://github.com/Legendgp/BackgroundPositioningContinuesToUpload 另外也有一個簡單的鬧鐘的dome https://github.com/Legendgp/alarmClock

我們知道,到我們程式從前臺退到後臺(安home)鍵後,將執行程式的委託方法。 //當應用程式掉到後臺時,執行該方法

- (void)applicationDidEnterBackground:(UIApplication*)application
{
}```
我們已經知道:
當一個iOS應用被送到後臺,它的主執行緒會被暫停。你用`NSThread的detachNewThreadSelector:toTar get:withObject:`類方法建立的執行緒也被掛起了。
我們假設有這麼一種情況:
當我們的應用程式從前臺被送到了後臺。
這時候,我們的程式將執行委託方法`applicationDidEnterBackground`。但是,這時候,應用程式只給了我們可憐的一點點時間(也就是秒級別的)來處理東西,然後,所有的執行緒都被掛起了。
而實際中,我們可能需要更長的時間來完成我們的需要的必要操作:
**1.我們需要在應用程式推到後臺時,能夠有足夠的時間來完成將資料儲存到遠端伺服器的操作。**
**2.有足夠的時間記錄一些需要的資訊操作。**
怎麼辦?!因為我們需要的時間可能會有點長,而預設情況下,iOS沒有留給我們足夠的時間。
悲劇了……
總需要有一個辦法來解決~~~~
**向iOS申請,在後臺完成一個Long-Running Task任務**
當一個iOS應用被送到後臺,它的主執行緒會被暫停。你用`NSThread`的`detachNewThreadSelector:toTar get:withObject:`類方法建立的執行緒也被掛起了。
如果你想在後臺完成一個長期任務,就必須呼叫`UIApplication`的`beginBackgroundTaskWithExpirationHandler:`例項方法,來向iOS借點時間。
預設情況下,如果在這個期限內,長期任務沒有被完成,iOS將終止程式。
怎麼辦?可以使用`beginBackgroundTaskWithExpirationHandler:`例項方法,來向iOS再借點時間。
既然是借時間,那麼就需要有一些約定俗成的方式。
先貼程式碼吧:
**1.專案的AppDelegate.h檔案中**
宣告一個UIBackgroundTaskIdentifier,相當於一個借據吧。告訴iOS,我們的程式將要借更多的時間來完成**Long-Running Task**任務。
複製程式碼

@property(nonatomic,unsafe_unretained)UIBackgroundTaskIdentifier backgroundTaskIdentifier; @property(nonatomic,strong)NSTimer*myTimer;``` 2.專案的AppDelegate.m檔案中 1.注意在applicationDidEnterBackground方法中,完成借據的流程 即:

self.backgroundTaskIdentifier=[applicationbeginBackgroundTaskWithExpirationHandler:^(void) {
      [selfendBackgroundTask];
}];```
//當應用程式掉到後臺時,執行該方法
//當一個iOS應用被送到後臺,它的主執行緒會被暫停。你用`NSThread`的`detachNewThreadSelector:toTar get:withObject:`類方法建立的執行緒也被掛起了。
//如果你想在後臺完成一個長期任務,就必須呼叫`UIApplication`的`beginBackgroundTaskWithExpirationHandler:`例項方法,來向iOS借點時間。
//預設情況下,如果在這個期限內,長期任務沒有被完成,iOS將終止程式。
//怎麼辦?可以使用`beginBackgroundTaskWithExpirationHandler:`例項方法,來向iOS再借點時間。
複製程式碼
  • (void)applicationDidEnterBackground:(UIApplication*)application { //使用這個方法來釋放公共的資源、儲存使用者資料、停止我們定義的定時器(timers)、並且儲存在程式終止前的相關資訊。 //如果,我們的應用程式提供了後臺執行的方法,那麼,在程式退出時,這個方法將代替applicationWillTerminate方法的執行。 //標記一個長時間執行的後臺任務將開始 //通過除錯,發現,iOS給了我們額外的10分鐘(600s)來執行這個任務。 self.backgroundTaskIdentifier=[applicationbeginBackgroundTaskWithExpirationHandler:^(void) { //當應用程式留給後臺的時間快要到結束時(應用程式留給後臺執行的時間是有限的), 這個Block塊將被執行 //我們需要在次Block塊中執行一些清理工作。 //如果清理工作失敗了,那麼將導致程式掛掉 //清理工作需要在主執行緒中用同步的方式來進行 [selfendBackgroundTask]; }]; //模擬一個Long-Running Task self.myTimer=[NSTimerscheduledTimerWithTimeInterval:1.0f target:self selector:@selector(timerMethod:)userInfo:nil repeats:YES]; }``` 2.完成後,要告訴iOS,任務完成,提交完成申請“好借好還”:
- (void) endBackgroundTask{
   dispatch_queue_tmainQueue =dispatch_get_main_queue();
   AppDelegate*weakSelf =self;
   dispatch_async(mainQueue, ^(void) {
   AppDelegate*strongSelf = weakSelf;
      if(strongSelf !=nil){
        [strongSelf.myTimerinvalidate];//停止定時器
        //每個對beginBackgroundTaskWithExpirationHandler:方法的呼叫,必須要相應的呼叫endBackgroundTask:方法。這樣,來告訴應用程式你已經執行完成了。
        //也就是說,我們向iOS要更多時間來完成一個任務,那麼我們必須告訴iOS你什麼時候能完成那個任務。
        //也就是要告訴應用程式:“好借好還”嘛。
        //標記指定的後臺任務完成
        [[UIApplicationsharedApplication]endBackgroundTask:self.backgroundTaskIdentifier];
        //銷燬後臺任務識別符號
        strongSelf.backgroundTaskIdentifier=UIBackgroundTaskInvalid;
      }
  });
}```
//模擬的一個Long-Running Task方法
複製程式碼
  • (void) timerMethod:(NSTimer*)paramSender{ // backgroundTimeRemaining屬性包含了程式留給的我們的時間 NSTimeIntervalbackgroundTimeRemaining = [[UIApplicationsharedApplication]backgroundTimeRemaining]; if(backgroundTimeRemaining ==DBL_MAX){ NSLog(@"Background Time Remaining = Undetermined"); }else{ NSLog(@"Background Time Remaining = %.02f Seconds", backgroundTimeRemaining); } }``` 3.記住,借和換必須成雙成對! 具體的解釋,我也寫在了方法中,如果有錯誤之處,還希望能夠指正!謝謝! 4.如果,程式提前完成了,也可以提前結束:
[[UIApplicationsharedApplication]endBackgroundTask:self.backgroundTaskIdentifier];
self.backgroundTaskIdentifier=UIBackgroundTaskInvalid;```
**向iOS申請,在後臺無限時間**
經過證明,即使時執行Long-Running Task 任務,當程式被調到後臺後,也是有時間限制的。一般為10分總(600s)。如何向程式申請無限時間呢?!
那就欺騙iOS系統吧。讓它感覺你的程式還是在執行。
那就在後臺用AVAudioPlayer無限迴圈播放一個音訊檔案。
呵呵,如果播放一個無聲音的音訊檔案呢?!!
步驟:
**1.在plish檔案中加入背景播放的支援。**
加入項:`Required background modes` 並設定為:`audio`
**2.初始化一個AVAudioPlayer音訊,並且無限制的播放下去。**
複製程式碼
  • (void)viewDidLoad { [superviewDidLoad]; dispatch_queue_tdispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0); dispatch_async(dispatchQueue, ^(void) { NSErroraudioSessionError =nil; AVAudioSessionaudioSession = [AVAudioSessionsharedInstance]; if([audioSessionsetCategory:AVAudioSessionCategoryPlaybackerror:&audioSessionError]){ NSLog(@"Successfully set the audio session."); }else{ NSLog(@"Could not set the audio session"); } NSBundlemainBundle = [NSBundlemainBundle]; NSStringfilePath = [mainBundlepathForResource:@"mySong"ofType:@"mp3"]; NSDatafileData = [NSDatadataWithContentsOfFile:filePath]; NSErrorerror =nil; self.audioPlayer= [[AVAudioPlayeralloc]initWithData:fileDataerror:&error]; if(self.audioPlayer!=nil){ self.audioPlayer.delegate=self; [self.audioPlayersetNumberOfLoops:-1]; if([self.audioPlayerprepareToPlay] && [self.audioPlayerplay]){ NSLog(@"Successfully started playing..."); }else{ NSLog(@"Failed to play."); } }else{ } }); }``` 搞定~~~~

相關文章