UIApplicationState在iOS 7上处于后台活动状态



我用beginBackgroundTaskWithExpirationHandler:^{}设置了一个后台任务,甚至在使用结束任务后

    if ([[UIDevice currentDevice] isMultitaskingSupported]) {
    [[UIApplication sharedApplication] endBackgroundTask:backgroundTaskID];
    backgroundTaskID = UIBackgroundTaskInvalid;
    }
    NSLog(@"App State -- %d", [[UIApplication sharedApplication] applicationState]);

    if([[UIApplication sharedApplication] applicationState] == UIApplicationStateActive)
    {
       //OpenGL operations
    }

我得到的是UIApplicationStateActive。这是个虫子吗?否则我该如何确定该应用程序确实在后台?

与其依赖applicationState值,不如在后台任务结束时发布自定义通知?

设置为自定义通知的观察员:

- (void)viewDidLoad
{
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(backgroundTaskDidFinish:) name:@"BackgroundTaskDidFinish" object:<either nil or the object that will post the notification>];
}

当后台任务完成时发布您的自定义通知

if ([[UIDevice currentDevice] isMultitaskingSupported]) {
    [[UIApplication sharedApplication] endBackgroundTask:backgroundTaskID];
    backgroundTaskID = UIBackgroundTaskInvalid;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"BackgroundTaskDidFinish" object:self]
}

响应通知,当你的应用程序真正返回到活动状态时,它应该会收到

- (void)backgroundTaskDidFinish:(NSNotification *)notification
{
   //OpenGL operations
}

或者,您可以查找其他通知消息之一,以表明您的应用程序确实处于活动状态。

例如,将您的对象添加为UIApplicationWillEnterForeground的观察者。在收到通知时设置BOOL值。然后,查找BOOL值和UIApplicationState值。

当然,在某个时候,你必须清除BOOL——比如说,当你开始后台任务时——所以除非应用程序真的激活了,否则它将是NO。

您可以尝试使用NSNotification:来确定它

- (void)viewDidLoad {
[super viewDidLoad];
UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:app];
}
- (void)applicationWillResignActive:(NSNotification *)notification {
//do what you want when your app is in background
}

相关内容

  • 没有找到相关文章

最新更新