根据用户需求,在执行任务时因外部因素程序退到后台;一段时间之后回来能继续在当前页面操作。
@property (nonatomic, assign)BOOL goingToQuit;
//自定义停留时间
#define KILL_IN_BACKGROUND_AFTER_SECS3600
// APP进入后台
- (void)applicationDidEnterBackground:(UIApplication *)application
{
[self comeToBackgroundMode];
//环信调用applicationDidEnterBackground 后会导致应用回到后台就被杀死
//[[EMClient sharedClient] applicationDidEnterBackground:application];
}
/*
*退出后台保证应用短时间内不被杀死
**/
-(void)comeToBackgroundMode{
self.goingToQuit = YES;
UIApplication* app = [UIApplication sharedApplication];
UIBackgroundTaskIdentifier __block bgTask;//设置后台任务ID
//开始申请一些额外的时间来处理任务,延迟系统挂起你的应用
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
//退到后台后30秒进入
[app endBackgroundTask:bgTask];//告诉系统,任务完成了,可以挂起APP了
bgTask =UIBackgroundTaskInvalid;
}];
//过期处理
if(UIBackgroundTaskInvalid != bgTask) {
// Start the long-running task to kill app after some secs and return immediately.
dispatch_after( dispatch_time(DISPATCH_TIME_NOW, KILL_IN_BACKGROUND_AFTER_SECS * 1e09),
dispatch_get_main_queue(), ^{
if(self.goingToQuit){
self.goingToQuit=NO;
exit(0);
}
[app endBackgroundTask: bgTask];
});
}
}
网友评论