每次我的应用程序从挂起模式唤醒时,我正在记录(写入文件)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];
}];
}
根据文档,如果应用程序位于前台,则backgroundTimeRemaining
的值可能很大:
当应用程序在前台运行时,此属性中的值 仍然适当大。
但这不是一个例子。我的方法被执行,因为应用程序状态等于UIApplicationStateBackground
。
我在这里缺少什么?
答案 0 :(得分:0)
是的,根据文件:
如果app在,则backgroundTimeRemaining的值可能很大 前景。
在提供正确的applicationDidEnterBackground
之前,backgroundTimeRemaining
需要一些时间在州之间。这应该在~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");
}
}
答案 1 :(得分:0)
这可能是由于您记录backgroundTimeRemaining
的方式。在获得后台任务后尝试输入:
UIApplication *app = [UIApplication sharedApplication];
long appState = (long)app.applicationState;
if (appState == UIApplicationStateBackground) {
__block UIBackgroundTaskIdentifier task = [app beginBackgroundTaskWithExpirationHandler:^{
[app endBackgroundTask:task];
task = UIBackgroundTaskInvalid;
[Logger logIntoFileNamed:@"log" withContent:@" expiration handler executed " andPrettyTime:true];
}];
NSTimeInterval backgroundTimeRemaining = app.backgroundTimeRemaining;
[Logger logIntoFileNamed:@"log" withContent:[NSString stringWithFormat:@" state %ld, background time remaining %.2f", appState, backgroundTimeRemaining] andPrettyTime:true];
}