日常小知识点小问题

iOS app 后台长时间保活

2018-07-13  本文已影响637人  不是特别闷骚的三石

废话不多说,上代码

- (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.timer = [NSTimer scheduledTimerWithTimeInterval:30 target:self selector:@selector(readyToSend) userInfo:nil repeats:NO];

   [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.timer invalidate];

  self.timer = nil;

  [self.bgTimer invalidate];

  self.bgTimer = nil;

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

  self.bgTask = UIBackgroundTaskInvalid;

}

上一篇下一篇

猜你喜欢

热点阅读