我们知道在后台模式下运行的应用程序存在一些限制。例如,NSTimer不起作用。我试着写一个像这样的“Timer”,可以在后台模式下工作。
-(UIBackgroundTaskIdentifier)startTimerWithInterval:(NSTimeInterval)interval run:(void (^)())runBlock complete:(void (^)())completeBlock
{
NSTimeInterval delay_in_seconds = interval;
dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, delay_in_seconds * NSEC_PER_SEC);
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
// ensure the app stays awake long enough to complete the task when switching apps
UIBackgroundTaskIdentifier taskIdentifier = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
completeBlock();
}];
NSLog(@"remain task time = %f,taskId = %d",[UIApplication sharedApplication].backgroundTimeRemaining,taskIdentifier);
dispatch_after(delay, queue, ^{
// perform your background tasks here. It's a block, so variables available in the calling method can be referenced here.
runBlock();
// now dispatch a new block on the main thread, to update our UI
dispatch_async(dispatch_get_main_queue(), ^{
completeBlock();
[[UIApplication sharedApplication] endBackgroundTask:taskIdentifier];
});
});
return taskIdentifier;
}
我这样调用了这个函数:
-(void)fire
{
self.taskIdentifier = [self startTimerWithInterval:10
run:^{
NSLog(@"timer!");
[self fire];
}
complete:^{
NSLog(@"Finished");
}];
}
除了存在一个问题外,此计时器工作正常。后台任务的最长时间是10分钟。(请参考startTimerWithInterval中的NSLog)。
如果有办法使我的计时器工作超过10分钟?顺便说一句,我的应用程序是一个BLE应用程序,我已经将UIBackgroundModes设置为蓝牙中心。