后台任务

来源:互联网 发布:隼龙 知乎 编辑:程序博客网 时间:2024/05/01 01:20

http://www.ppsim.com/blog/index.php/2011/04/418

http://www.informit.com/articles/article.aspx?p=1646438&seqNum=6

 

在iphone4模拟器上测试:


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {   
        [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];

    UIApplication* app = [UIApplication sharedApplication];

//UIBackgroundTaskIdentifier iBgTask;

    iBgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        [app endBackgroundTask:iBgTask];
        iBgTask = UIBackgroundTaskInvalid;
    }];

}


-(void)onTimer
{   
    NSString* urlstr=@"http://...";
    NSURL* url=[NSURL URLWithString:urlstr];
    NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
    [[NSURLConnection alloc] initWithRequest:request delegate:self];
   
    UIApplication* app = [UIApplication sharedApplication];
    NSTimeInterval timeRemaining=app.backgroundTimeRemaining; //后台剩余时间,秒.
    NSNumber* number=[NSNumber numberWithDouble:timeRemaining];
    NSLog(@"backgroundTimeRemaining:%@",[number stringValue]);
}

 

测试结果:当在前台时,timeRemaining是一个很大的值, 程序转到后台后,得到timeRemaining是600秒.

当timeRemaining降到快到5时,进入了[app endBackgroundTask:iBgTask];后台运行结束.

 

如果把iBgTask声明为了局部变量,此时会报Can't endBackgroundTask: no background task exists with identifier 4d09910, or it may have already been ended. Break in UIApplicationEndBackgroundTaskError() to debug.但却在这之后NSTimer仍然继续正常执行,onTimer中执行的网络操作正常,timeRemaining会变为负数.

不执行endBackgroundTask也会正常继续.

原创粉丝点击