天天看點

app進入背景申請10分鐘活躍時間-b

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;
}      

繼續閱讀