美文网首页日常小知识点小问题
iOS app 后台长时间保活

iOS app 后台长时间保活

作者: 不是特别闷骚的三石 | 来源:发表于2018-07-13 10:44 被阅读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;

    }

    相关文章

      网友评论

      • Charles_Zhang:你好,按照你的方法在模拟器下运行 没问题,但是在真机上还是只能运行三分钟。能否将整个 .m文件的代码贴出来 或是截图来看下?
      • 封竹:if ([UIApplication sharedApplication].backgroundTimeRemaining < 60) { 这个执行一次后,计时器 makeMoreTime 就不执行了。
        封竹:@不是特别闷骚的三石 每次到 后台挂起时间 剩余 60 秒后 计时器 就不执行了。 在这 之前可以执行
        封竹:@不是特别闷骚的三石 设置的是 YES
        不是特别闷骚的三石:repeat那儿没设置成yes吧
      • 无星灬:老哥,能上整个Appdelegate。m文件吗:joy:

      本文标题:iOS app 后台长时间保活

      本文链接:https://www.haomeiwen.com/subject/pxkjpftx.html