当设备进入后台时,我有一个计时器在运行,因为我想对服务中的少量数据进行检查。我在app委托中的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分钟,所以大多数设备将在这之前被锁定很久,甚至是滴答一次。
谢谢
发布于 2015-05-15 16:33:01
以下是几点意见:
beginBackgroundTaskWithExpirationHandler版本中,iOS只给你30秒(以前是3分钟)。所以在五分钟内发射定时器是行不通的。
你可以用[[UIApplication sharedApplication] backgroundTimeRemaining]查询你还剩下多少时间。因此,只需从主线程调用scheduledTimerWithTimeInterval,您就完成了。除非绝对必要,否则使用GCD工作线程和run循环是没有意义的(即使这样,我也可能创建自己的线程,并在其中添加一个run循环)。
顺便说一句,如果绝对有必要在某个后台调度队列上安排计时器,那么使用调度计时器可能更容易一些。它完全消除了运行循环的要求。
- 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.https://stackoverflow.com/questions/30263427
复制相似问题