8

当设备进入后台时,我有一个计时器正在运行,因为我想检查我的服务中的少量数据。我在应用程序委托的 applicationDidEnterBackground 方法中使用以下代码

    UIApplication *app = [UIApplication sharedApplication];

//create new uiBackgroundTask
__block UIBackgroundTaskIdentifier bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
    [app endBackgroundTask:bgTask];
    bgTask = UIBackgroundTaskInvalid;
}];

//and create new timer with async call:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    //run function methodRunAfterBackground
    NSString *server = [variableStore sharedGlobalData].server;
    NSLog(@"%@",server);
    if([server isEqual:@"_DEV"]){
        arrivalsTimer = [NSTimer scheduledTimerWithTimeInterval:30 target:self selector:@selector(getArrivals) userInfo:nil repeats:YES];
    }
    else {
        arrivalsTimer = [NSTimer scheduledTimerWithTimeInterval:300 target:self selector:@selector(getArrivals) userInfo:nil repeats:YES];
    }
    [[NSRunLoop currentRunLoop] addTimer:arrivalsTimer forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] run];
});

这工作得很好,直到设备自动锁定然后计时器停止计时。关于如何阻止这种情况发生的任何建议?默认实时时间为 5 分钟,因此大多数设备将在此时间甚至滴答一次之前就被锁定。

谢谢

4

1 回答 1

4

几点观察:

  1. 正如 H 先生指出的那样,beginBackgroundTaskWithExpirationHandler在当代 iOS 版本中只给你 30 秒(以前是 3 分钟)。因此,尝试在五分钟内触发计时器是行不通的。

    您可以使用[[UIApplication sharedApplication] backgroundTimeRemaining]查询您还剩多少时间。

  2. 当设备锁定时,后台任务继续。您不应该看到应用程序终止。如果用户通过“双击主页按钮并在任务切换器屏幕上向上滑动”手动终止应用程序,则会终止后台任务,但不会简单地锁定设备。

  3. 关于计时器的一些评论:

    • 该代码正在将计时器添加到后台队列。这通常是没有必要的。仅仅因为应用程序处于后台状态,您仍然可以继续将主运行循环用于计时器等。

      所以,只需scheduledTimerWithTimeInterval从主线程调用就可以了。除非绝对必要,否则将 GCD 工作线程与运行循环一起使用是没有意义的(即便如此,我可能会创建自己的线程并为其添加运行循环)。

      顺便说一句,如果绝对有必要在某个后台调度队列上安排计时器,那么使用调度计时器可能更容易。它完全消除了运行循环的要求。

    • 顺便说一句,它不适合scheduledTimerWithTimeIntervaladdTimer. 您调用scheduledTimerWithTimeInterval创建一个计时器并将其添加到当前运行循环。如果要将其添加到另一个运行循环,请使用timerWithTimeInterval然后调用。addTimer

于 2015-05-15T16:33:01.880 回答