你可以同时使用两个选项以获得更好的结果。例如,当应用程序从didFinishLaunchingWithOptions:激活时,使用选项2;当应用程序从- (void)applicationDidBecomeActive:(UIApplication *)application或- (void)applicationWillEnterForeground:(UIApplication *)application启用时,使用选项1。
选项1-最简单的方法是在后台运行循环中安排一个NSTimer。我建议您在应用程序委托中实现以下代码,并从applicationWillResignActive:中调用setupTimer。
- (void)applicationWillResignActive:(UIApplication *)application
{
[self performSelectorInBackground:@selector(setupTimerThread) withObject:nil];
}
-(void)setupTimerThread;
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
NSTimer* timer = [NSTimer timerWithTimeInterval:10 * 60 target:self selector:@selector(triggerTimer:) userInfo:nil repeats:YES];
NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
[runLoop addTimer:timer forModes:NSRunLoopCommonModes];
[runLoop run];
[pool release];
}
-(void)triggerTimer:(NSTimer*)timer;
{
}
in appDelegate .h
UIBackgroundTaskIdentifier bgTask;
在 appDelegate .m 文件中
- (void)applicationDidEnterBackground:(UIApplication *)application
{
UIApplication* app = [UIApplication sharedApplication];
NSAssert(bgTask == UIBackgroundTaskInvalid, nil);
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
dispatch_async(dispatch_get_main_queue(), ^{
if (bgTask != UIBackgroundTaskInvalid)
{
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}
});
}];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
if (bgTask != UIBackgroundTaskInvalid)
{
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}
});
});
NSLog(@"app entering background");
}
或者您可以通过以下方式在后台线程上运行NSTimer(我有意地泄漏了线程对象):
-(void)startTimerThread;
{
NSThread* thread = [[NSThread alloc] initWithTarget:self selector:@selector(setupTimerThread) withObject:nil];
[thread start];
}
尝试使用上面的代码。我们同时使用这两个选项,对我们来说效果很好。祝你好运。