您可以同时关注两者以获得更好的结果。例如,当应用程序从 didFinishLaunchingWithOptions: 处于活动状态时使用选项 2,当应用程序启用时使用选项 1
- (void)applicationDidBecomeActive:(UIApplication *)application 或 - (void)applicationWillEnterForeground:(UIApplication *)application
选项 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;
{
// Do your stuff
}
在 appDelegate .h
UIBackgroundTaskIdentifier bgTask;
在 appDelegate .m
- (void)applicationDidEnterBackground:(UIApplication *)application
{
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 = [app 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)
{
[app 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.
// Synchronize the cleanup call on the main thread in case
// the expiration handler is fired at the same time.
dispatch_async(dispatch_get_main_queue(), ^{
if (bgTask != UIBackgroundTaskInvalid)
{
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}
});
});
NSLog(@"app entering background");
/*
Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
*/
}
或者您可以使用类似这样的方式在后台线程上运行 NSTimer(我故意泄漏线程对象):
-(void)startTimerThread;
{
NSThread* thread = [[NSThread alloc] initWithTarget:self selector:@selector(setupTimerThread) withObject:nil];
[thread start];
}
试试上面的代码。我们使用这两个选项对我们来说都很好。祝你好运