在iOS中后台执行程序

iOS默认是不支持程序的后台运行的,但是也提供了一些途径来使得程序能后在切入后台时也正常工作。

其中抛开常见的后台音乐等擦边球手段,比较正规的就是声请一个后台任务,但是任务的执行时间被限制为10分钟,并且在10分钟之后再次声请也不会成功。

本文采用的手段就是在声请10分钟的任务时间到达时利用一个while(true)将当次runloop挂起等待程序切回时再跳出。

核心代码如下

声请后台任务

1 UIApplication *application = [UIApplication sharedApplication];
2     __block UIBackgroundTaskIdentifier background_task;
3     //Create a task object
4     background_task = [application beginBackgroundTaskWithExpirationHandler: ^ {
5         [self hold];
6         [application endBackgroundTask: background_task];
7         background_task = UIBackgroundTaskInvalid;
8     }];

hold住限时任务结束时的runloop

1 - (void)hold
2 {
3     _holding = YES;
4     while (_holding) {
5         [NSThread sleepForTimeInterval:1];
6         /** clean the runloop for other source */
7         CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0, TRUE);
8     }
9 }

 

之后作者发现不需要先声请10分钟限时后台任务,直接在程序切出后台时挂起一个while(true)就可以达到相同的效果。

 实验证明不申请后台task程序虽然会执行,但是切出去后返回无法正常显示UI。

源码参见https://github.com/joexi/BackgroundRunner

posted @ 2013-08-27 23:17  Joe.xi  阅读(738)  评论(0)    收藏  举报