iOS 程式退到後台,如何繼續執行任務

來源:互聯網
上載者:User

標籤:

程式從前台退到後,將執行程式的委託方法。

- (void)applicationDidEnterBackground:(UIApplication *)application

{

}

問題:當應用被送到後台,主線程就會被暫停。用 NSThread 的 detachNewThreadSelector:toTar get:withObject:類方法建立的線程也被掛起。 情境:應用從前台退到背景程式執行代理方法 applicationDidEnterBackground。這時候,我們只有很短的時間來處理需要處理的工作,隨後,所有的線程就都被掛起了。實際上,我們需要更長的時間來完成我們的需要的必要操作:比如:

1.將資料儲存到遠程伺服器的操作。

2.記錄一些需要的資訊操作。

參考解決方案 :  向iOS申請,在後台完成一個Long-Running Task任務

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 =[application beginBackgroundTaskWithExpirationHandler:^( void) {

        [self endBackgroundTask];

   }];

 // 當應用程式掉到後台時,執行該方法

- (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];

   

}

2.完成後,要告訴iOS,任務完成,提交完成申請“好借好還”:

 [[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);

  }

}

3.記住,借和換必須成雙成對!具體的解釋,我也寫在了方法中,如果有錯誤之處,還希望能夠指正!謝謝! 4.如果,程式提前完成了,也可以提前結束:

 [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskIdentifier];

            self.backgroundTaskIdentifier = UIBackgroundTaskInvalid;

向iOS申請,在後台無限時間經過證明,即使時執行Long-Running Task 任務,當程式被調到後台後,也是有時間限制的。一般為10分總(600s)。如何向程式申請無限時間呢?!那就欺騙iOS系統吧。讓它感覺你的程式還是在運行。那就在後台用 AVAudioPlayer無限迴圈播放一個音頻檔案。呵呵,如果播放一個無聲音的音頻檔案呢?!!步驟: 1.在plish檔案中加入背景播放的支援。加入項:Required background modes。並設定為:audio 2.初始化一個AVAudioPlayer音頻,並且無限制的播放下去。

- (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 {

            

     }

  });

}

 

iOS 程式退到後台,如何繼續執行任務

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.