iOS应用程序转到后台后套接字连接被杀死

时间:2013-02-14 13:53:35

标签: ios iphone multitasking

我使用iPhone应用聊天使用套接字连接与服务器通信。当应用程序移动到后台时,我可以看到服务器能够与应用程序通信大约5分钟。但在此之后,套接字连接被破坏。但是应用程序一移到后台就会停止执行。为什么套接字连接保持5分钟而不是应用程序执行。苹果指定连接将保持的确切时间。

2 个答案:

答案 0 :(得分:9)

通过在applicationDidEnterBackground中使用以下代码,您可以获得600秒(10分钟)的最长时间:

if ([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]) { //Check if our iOS version supports multitasking I.E iOS 4
if ([[UIDevice currentDevice] isMultitaskingSupported]) { //Check if device supports mulitasking
    UIApplication *application = [UIApplication sharedApplication]; //Get the shared application instance
    __block UIBackgroundTaskIdentifier background_task; //Create a task object
    background_task = [application beginBackgroundTaskWithExpirationHandler: ^ {
        [application endBackgroundTask: background_task]; //Tell the system that we are done with the tasks
        background_task = UIBackgroundTaskInvalid; //Set the task to be invalid
        //System will be shutting down the app at any point in time now
    }];
    //Background tasks require you to use asyncrous tasks
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //Perform your tasks that your application requires
        NSLog(@"\n\nRunning in the background!\n\n");
        [application endBackgroundTask: background_task]; //End the task so the system knows that you are done with what you need to perform
        background_task = UIBackgroundTaskInvalid; //Invalidate the background_task
    });
  }
}

可在此处找到文档http://disanji.net/iOS_Doc/#documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html

我刚刚实现了backgroundTaskIdentifier对象并使background_task无效以检查时间,应用程序处于活动状态且运行600秒。您甚至可以使用此

获得剩余时间
NSLog(@"Time remaining: %f", application.backgroundTimeRemaining);

答案 1 :(得分:1)

来自Apple的IOS Programming Guide

  

进入后台状态的大多数应用程序都会移动到   此后不久暂停状态。在这种状态下,   应用程序不执行任何代码,可能会从内存中删除   随时。为用户提供特定服务的应用程序   可以请求后台执行时间以提供这些   服务。

这至少解释了为什么应用停止执行。为什么您的服务器仍然可以与您的应用程序通信5分钟,因为您设置了更长的时间,并且没有在您的应用程序进入后台时明确关闭套接字连接。

相关问题