iOS app 后台长时间保活

废话不多说,上代码


- (void)applicationDidEnterBackground:(UIApplication *)application {

  // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.

  // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

   [self comeToBackground];

}

-(void)comeToBackground{

  //初始化一个后台任务BackgroundTask,这个后台任务的作用就是告诉系统当前app在后台有任务处理,需要时间

  UIApplication* app = [UIApplication sharedApplication];

  self.bgTask = [app beginBackgroundTaskWithExpirationHandler:^{

    [app endBackgroundTask:self.bgTask];

    self.bgTask = UIBackgroundTaskInvalid;

  }];

  //开启定时器 不断向系统请求后台任务执行的时间

  self.bgTimer = [NSTimer scheduledTimerWithTimeInterval:25.0 target:self selector:@selector(makeMoreTime) userInfo:nil repeats:YES];

  [self.bgTimer fire];

}

-(void)makeMoreTime {

  //如果系统给的剩余时间小于60秒 就终止当前的后台任务,再重新初始化一个后台任务,重新让系统分配时间,这样一直循环下去,保持APP在后台一直处于active状态。


  if ([UIApplication sharedApplication].backgroundTimeRemaining < 60) {


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

    self.bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{


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

      self.bgTask = UIBackgroundTaskInvalid;

    }];

  }

}

- (void)applicationWillEnterForeground:(UIApplication *)application {

  // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.

//回到前台将用到的timer销毁,很重要

  [self.bgTimer invalidate];

  self.bgTimer = nil;

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

  self.bgTask = UIBackgroundTaskInvalid;

}

你可能感兴趣的:(iOS app 后台长时间保活)