在我的iPhone应用程序中,我有一个后台任务,在应用程序进入后台状态时开始运行。 该任务运行良好,并且以这样的循环结构化:iPhone后台任务在某个时间点停止运行
运行。 睡5分钟。 运行。 睡5分钟。
等
出于某种原因,该任务将停止一定时间后运行......说半小时到一小时。
任何人都可以帮我理解为什么吗? 这里是后台任务代码:
- (void)applicationDidEnterBackground:(UIApplication *)application {
NSLog(@"Application entered background state.");
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"bgCheckSwitch"] == YES) {
//UIApplication* app = [UIApplication sharedApplication];
// Request permission to run in the background. Provide an
// expiration handler in case the task runs long.
NSAssert(bgTask == UIBackgroundTaskInvalid, nil);
bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
// Synchronize the cleanup call on the main thread in case
// the task actually finishes at around the same time.
dispatch_async(dispatch_get_main_queue(), ^{
if (bgTask != UIBackgroundTaskInvalid)
{
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}
});
}];
// Start the long-running task and return immediately.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Do the work associated with the task.
[someClass doSomeThing]; //The actual method performed by the task. The looping is in the method.
dispatch_async(dispatch_get_main_queue(), ^{
if (bgTask != UIBackgroundTaskInvalid)
{
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}
});
});
}
}
您的后台任务如何运行一个小时?使用类似的代码我的任务在一分钟后死亡。基本上它只是一个非重复的计时器。你如何实现“睡5分钟”? - 谢谢 – Dimitris 2010-10-18 09:30:17