applicationWillEnterForeground后的黑屏

时间:2011-05-11 11:44:04

标签: iphone objective-c multithreading ios

我的iOS应用程序中的多任务处理似乎有问题。 我有一个NSTimer运行,它会更新屏幕上的一些内容和另一个NSTimer,它将在定义的时间间隔后才会被触发一次。

问题是:我想对那场火灾事件做出反应。我的应用程序是否在前台。

我使用以下代码来跟踪计时器:

-(void)backgroundThreadStarted {
  NSAutoreleasePool* thePool = [[NSAutoreleasePool alloc] init];

  // create a scheduled timer
  NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(backgroundThreadFire:) userInfo:nil repeats:YES];
  [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];

  m_isBackgroundThreadToTerminate = NO;

  // create the runloop
  double resolution = 300.0;
  BOOL isRunning;
  do {
    // run the loop!
    NSDate* theNextDate = [NSDate dateWithTimeIntervalSinceNow:resolution]; 
    isRunning = [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:theNextDate]; 
    // occasionally re-create the autorelease pool whilst program is running
    [thePool release];
    thePool = [[NSAutoreleasePool alloc] init];            
  } while(isRunning==YES && m_isBackgroundThreadToTerminate==NO);

  [thePool release];
}

-(void)backgroundThreadFire:(id)sender {
  // do repeated work every one second here

  // when thread is to terminate, call [self backgroundThreadTerminate];

}

-(void)backgroundThreadTerminate {
  m_isBackgroundThreadToTerminate = YES;
  CFRunLoopStop([[NSRunLoop currentRunLoop] getCFRunLoop]);
}

(在此处找到:http://www.cocoadev.com/index.pl?RunLoop

我在backgroundThreadStarted上呼叫-(void)applicationDidEnterBackground:(UIApplication *)application,在backgroundThreadTerminate呼叫- (void)applicationWillEnterForeground:(UIApplication *)application,我可以跟踪定时器。所以这很有效。

不幸的是,在返回应用程序后,整个屏幕都是黑色的。我尝试了不同的解决方案,我搜索了很多,但都没有用。

如果我在看到这个黑屏时最小化应用程序,我可以看到应用程序,同时它是动画到背景。

我错过了什么?

如果我不做这个backgroundThread的东西,屏幕显示正常。但是,我无法跟踪计时器。

提前致谢!

1 个答案:

答案 0 :(得分:2)

你正在使用AppKit(OS X)的代码而不是UIKit(iOS)。

您应该查看后台API,它将涉及处理didEnterBackground,并在那里使用beginBackgroundTaskWithExpirationHandler创建后台任务:

后台线程不是必需的(它们适用于在应用程序后台运行的内容,而您的应用程序仍在运行)。后台任务是一种让应用程序不再位于前台时运行常规应用程序代码(无UI交互)的方法。在本地通知服务之外,您将无法轻松地与用户就此进行通信(API更多是为了让您在离开应用程序后完成上传)。并且你的任务仅限于在后备后十分钟。

相关问题