我正在尝试理解当应用程序转到后台时NSThread是如何工作的。我在appdeligate中有以下代码:
- (void)applicationDidEnterBackground:(UIApplication *)application
{
[self backgroundHandler];
}
- (void)backgroundHandler {
NSInteger counter=0;int scontinue=true;
while(scontinue){
NSLog(@"counter:%d",counter++);
sleep(1)
}
} 当我转到后台时,它每隔1秒输出一个值。我已经让它打开了大约5分钟,它给了我:
counter:1
counter:2
...
counter:300 而且这种情况还在继续。但是,如果尝试进入前台,backgroundHandler不会退出while循环,我的应用程序也不会响应任何东西。
现在,我更改了applicationDideEnterBackground,并改为使用线程,即
- (void)applicationDidEnterBackground:(UIApplication *)application
{
[NSThread detachNewThreadSelector:@selector(backgroundHandler) toTarget:self withObject:nil];
}
- (void)backgroundHandler {
NSInteger counter=0;int scontinue=true;
while(scontinue){
NSLog(@"counter:%d",counter++);
//sleep(1) : I remove the sleep for the shake of the example
}
} 虽然我希望有与前一个案例相同的行为,但线程似乎在一段时间后被挂起。所以我得到的结果是:
counter:1
counter:2
...
counter:30 现在线程在这一点上阻塞了,没有执行任何东西。当我转到前台时,线程再次开始运行,即计数器增加并打印出来。应用程序再次正常运行。
上面的例子是我想要做的事情的一个相当简单的版本。我真正想要的是当应用程序转到后台与服务器通信时,只要用户不转到前台。当它消失时,任何通信都应该被终止。所以我真正想要的是上面几个简单例子的组合,即在while循环中转到后台时继续询问服务器,当我进入前台时我的应用程序开始正常响应并终止backgroundHandler for循环。
有什么帮助吗?
发布于 2016-01-27 18:23:16
- (void)applicationDidEnterBackground:(UIApplication *)application的主要用途是在应用程序进入后台时保存应用程序的状态。在这种情况下,如果应用程序开始使用大量的CPU或RAM,操作系统将根据手机的状态终止应用程序。
当您想要对服务器执行后台操作或服务时,可以通过在AppDelegate的- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions中调用[[UIApplication sharedApplication] setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];来启用后台拉取。
-(void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
//Add your code here
[self setBackgroundCheckInterval:UIBackgroundFetchResultNewData];
completionHandler(UIBackgroundFetchResultNewData);
}
- (void)setBackgroundCheckInterval:(NSInteger)resultCode
{
UIBackgroundRefreshStatus status = [UIApplication sharedApplication].backgroundRefreshStatus;
if (status == UIBackgroundRefreshStatusAvailable)
{
switch (resultCode)
{
case UIBackgroundFetchResultFailed :
[[UIApplication sharedApplication] setMinimumBackgroundFetchInterval:BACKGROUND_CHECK_INTERVAL_NO_NEW_DATA];
break;
case UIBackgroundFetchResultNewData :
[[UIApplication sharedApplication] setMinimumBackgroundFetchInterval:BACKGROUND_CHECK_INTERVAL_NEW_DATA];
break;
case UIBackgroundFetchResultNoData :
[[UIApplication sharedApplication] setMinimumBackgroundFetchInterval:BACKGROUND_CHECK_INTERVAL_NO_NEW_DATA];
break;
}
}
}https://stackoverflow.com/questions/35034346
复制相似问题