iOS:如何判断应用程序何时暂停



我想知道我的应用程序何时暂停?在一定时间内未激活或被用户终止的状态。我需要这个,因为我需要关闭网络套接字的连接。不过,我想在应用程序处于后台状态时保持连接。

我该怎么做?

感谢

您还可以添加Notification observer

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(receiveSuspendNotification:)
                                             name:UIApplicationWillResignActiveNotification
                                           object:nil];
- (void) receiveSuspendNotification:(NSNotification*)notif
{
}

方法将被调用,您可以执行所需的任务。

如果你的应用程序没有在后台注册运行,那么当收到UIApplicationDidEnterBackgroundNotification时,你的应用将在RAM中暂停。

在AppDelegate.m文件中,当用户点击主页按钮,应用程序将转到后台时,将调用此方法(在这里,你可以保持连接的实时性,但你应该阅读有关后台任务的苹果文档,因为如果应用程序保持在后台,你的连接就不可能永远实时。还有其他方法可以保持应用程序的最新状态,如推送通知更新等):

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

当应用程序被终止(从多任务处理中完全关闭)时,将调用此方法。

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

您可以在这些方法中处理您的连接。

最新更新