iOS 通常是不能在后台运行的,尤其是用户点击锁屏键,APP进入后台,网络立马断开等。如何解决这个问题呢?在APP进入后台,APP怎么争取一些时间来“善后”。代码如下:注:需要定义一个属性 UIBackgroundTaskIdentifier _bgTask;该代码可以自定义后台多长时间自动结束任务。
- (void) timerMethod:(NSTimer *)paramSender
{
/*这里处理后台需要的逻辑,不可太长*/
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
UIDevice * device = [UIDevice currentDevice];
if([device respondsToSelector:@selector(isMultitaskingSupported)] && [device isMultitaskingSupported])
{
self.pushTimer = [NSTimer scheduledTimerWithTimeInterval:30.0f target:self selector:@selector(timerMethod:) userInfo:nil repeats:YES];
//向iOS系统,借用10分钟(默认就是10分钟)时间。当调用beginBackgroundTaskWithExpirationHandler: 记得必须调用endBackgroundTask:方法,否则iOS会终止你的程序.
_bgTask = [application beginBackgroundTaskWithExpirationHandler:^
{
NSLog(@"后台10分钟运行完成,APP进程即将被挂起");
if(_pushTimer!=nil)
{
[_pushTimer invalidate];
}
[application endBackgroundTask:_bgTask];
_bgTask = UIBackgroundTaskInvalid;
}];
//如果想提前结束10分钟的后台运行,可在下面加逻辑,目前是空转.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSInteger remaining = [application backgroundTimeRemaining];
NSLog(@"remain %d S", remaining);
while (remaining > 30 && _bgTask != UIBackgroundTaskInvalid) {
sleep(15);
remaining = [application backgroundTimeRemaining];
NSLog(@"remain %d S", remaining);//iOS 7就只有180秒,但是超过这个时间程序依然可以运行
// if (remaining<=180) {//如果想提前结束10分钟的后台运行,打开这个if
// [application endBackgroundTask:_bgTask];
// _bgTask = UIBackgroundTaskInvalid;
// }
}
NSLog(@"background thread finished");
});
}
}