UIApplicationState在iOS 7的后台活动

时间:2013-11-25 19:14:32

标签: ios ios7 multitasking uiapplication backgrounding

我使用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。这是一个错误吗?我如何确定应用程序确实在后台?

2 个答案:

答案 0 :(得分:1)

如何在后台任务结束时发布自定义通知,而不是依赖于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。

答案 1 :(得分:0)

您可以尝试使用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
}