首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当设备锁定时后台任务停止?

当设备锁定时后台任务停止?
EN

Stack Overflow用户
提问于 2015-05-15 15:33:49
回答 1查看 3.6K关注 0票数 8

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

代码语言:javascript
复制
    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分钟,所以大多数设备将在这之前被锁定很久,甚至是滴答一次。

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-05-15 16:33:01

以下是几点意见:

  1. 正如H先生所指出的,在当代的beginBackgroundTaskWithExpirationHandler版本中,iOS只给你30秒(以前是3分钟)。所以在五分钟内发射定时器是行不通的。 你可以用[[UIApplication sharedApplication] backgroundTimeRemaining]查询你还剩下多少时间。
  2. 当设备锁定时,后台任务将继续。您不应该看到应用程序终止。如果用户通过“双击主按钮并在任务切换屏幕上滑动”手动终止应用程序,这将杀死后台任务,而不仅仅是锁定设备。
  3. 关于计时器的几点评论:

因此,只需从主线程调用scheduledTimerWithTimeInterval,您就完成了。除非绝对必要,否则使用GCD工作线程和run循环是没有意义的(即使这样,我也可能创建自己的线程,并在其中添加一个run循环)。

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

代码语言:javascript
复制
- BTW, it's not appropriate to use `scheduledTimerWithTimeInterval` with `addTimer`. You call `scheduledTimerWithTimeInterval` to create a timer and add it to the current run loop. You use `timerWithTimeInterval` and then call `addTimer` if you want to add it to another run loop.
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30263427

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档