每次我的应用程序从挂起模式唤醒时,我正在记录(写入文件)
backgroundTimeRemaining值,就在我开始使用到期处理程序的UIApplication后台任务之前,就像这样(在我的方法中发出网络请求):
if([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground){ [Logger logIntoFileNamed:@"log" withContent:[NSString stringWithFormat:@" state %ld,background time remaining %.2f",(long)[[UIApplication sharedApplication] applicationState],[[UIApplication sharedApplication] backgroundTimeRemaining ]] andPrettyTime:true]; UIApplication* app = [UIApplication sharedApplication]; __block UIBackgroundTaskIdentifier task = [app beginBackgroundTaskWithExpirationHandler:^{ [app endBackgroundTask:task]; task = UIBackgroundTaskInvalid; [Logger logIntoFileNamed:@"log" withContent:@" expiration handler executed " andPrettyTime:true]; }]; }
根据文档,如果app在前台,backgroundTimeRemaining的值可能很大:
While the app is running in the foreground,the value in this property
remains suitably large.
但这不是一个例子.我的方法被执行,因为应用程序状态等于UIApplicationStateBackground.
我在这里错过了什么?
解决方法
是的,根据文件:
A value of backgroundTimeRemaining can be big if app is in the
foreground.
在提供正确的backgroundTimeRemaining之前,applicationDidEnterBackground需要在状态之间进行一些时间.这应该在~180左右开始.使用dispatch_async在异步线程中运行它并过滤掉Foreground值(> 180).
- (void)applicationDidEnterBackground:(UIApplication *)application { if([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]) { NSLog(@"Multitasking Supported"); __block UIBackgroundTaskIdentifier background_task; background_task = [application beginBackgroundTaskWithExpirationHandler:^ { //Clean up code. Tell the system that we are done. [application endBackgroundTask: background_task]; background_task = UIBackgroundTaskInvalid; }]; //To make the code block asynchronous dispatch_async(dispatch_get_main_queue(),^{ //### background task starts NSLog(@"Running in the background\n"); while(TRUE) { //#### Filter Foreground Values if ([[UIApplication sharedApplication] backgroundTimeRemaining] < 180) { NSLog(@"Background time Remaining: %f",[[UIApplication sharedApplication] backgroundTimeRemaining]); [NSThread sleepForTimeInterval:1]; //wait for 1 sec } } //#### background task ends //Clean up code. Tell the system that we are done. [application endBackgroundTask: background_task]; background_task = UIBackgroundTaskInvalid; }); } else { NSLog(@"Multitasking Not Supported"); } }