Ios 后台和NSThread
我试图了解应用程序进入后台时NSThread是如何工作的。我在appdeligate中有以下代码:Ios 后台和NSThread,ios,objective-c,iphone,background,nsthread,Ios,Objective C,Iphone,Background,Nsthread,我试图了解应用程序进入后台时NSThread是如何工作的。我在appdeligate中有以下代码: - (void)applicationDidEnterBackground:(UIApplication *)application { [self backgroundHandler]; } - (void)backgroundHandler { NSInteger counter=0;int scontinue=true; while(sco
- (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循环,我的应用程序也不会响应任何内容
现在我更改了ApplicationIDEenterBackground,而是使用了一个线程,即
- (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
}
}
虽然我期望具有与前一个案例相同的行为,但线程似乎在某个ms之后保持不变。因此,我得到的结果是:
counter:1
counter:2
...
counter:30
现在线程在这一点上阻塞,没有执行任何操作。当我转到前台时,线程再次开始运行,即计数器增加,并且正在打印出来。应用程序再次正常运行
上面的例子是我要做的一个相当简单的版本。我真正想要的是,只要用户不去前台,应用程序什么时候去后台与服务器通信。当它停止时,任何通信都应该终止。因此,我真正想要的是上面简单示例的组合,即当转到后台while循环时,继续询问服务器,当我进入前台时,我的应用程序开始正常响应并终止backgroundHandler for循环
有什么帮助吗?应用程序的主要目的是在应用程序进入后台时保存应用程序的状态。在这种情况下,如果应用程序开始使用大量CPU或RAM,操作系统将根据手机的状态终止应用程序 当您要对服务器执行后台操作或服务时,通过调用
[[UIApplication sharedApplication]setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum]启用后台提取代码>在-(BOOL)应用程序中:(UIApplication*)应用程序使用AppDelegate的选项:(NSDictionary*)启动选项完成启动
-(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;
}
}
}
这些常量变量是什么?背景检查间隔时间没有新数据背景检查间隔时间新数据背景检查间隔时间没有新数据背景时间检查间隔时间没有新数据更详细,因为我对这一点很陌生,可以给我一本参考书或一本完整的例子来检查吗?背景检查间隔否新数据背景检查间隔新数据这些是为后台进程运行提供时间值的宏可以用来与服务器进行持续通信并等待不同的事件吗?例如,在与服务器连接的不同系统中,发生了一些事情,iPhone需要做些什么?