iOS限制后台时间
问题描述:
我需要在用户进入后台状态时运行一些代码。我在iOS 9上进入后台时的默认时间是10秒。我需要比多一点,所以我发现,这个代码将时间延长到3分钟:iOS限制后台时间
- (void)extendBackgroundRunningTime {
if (_backgroundTask != UIBackgroundTaskInvalid) {
// if we are in here, that means the background task is already running.
// don't restart it.
return;
}
NSLog(@"Attempting to extend background running time");
__block Boolean self_terminate = YES;
_backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithName:@"DummyTask" expirationHandler:^{
NSLog(@"Background task expired by iOS");
if (self_terminate) {
[[UIApplication sharedApplication] endBackgroundTask:_backgroundTask];
_backgroundTask = UIBackgroundTaskInvalid;
}
}];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(@"Background task started");
while (true) {
NSLog(@"background time remaining: %8.2f", [UIApplication sharedApplication].backgroundTimeRemaining);
[NSThread sleepForTimeInterval:1];
}
});
}
然而,我的任务并不需要所有这些额外的时间,我想作为保护尽可能多的电池。有什么方法可以使用这个或类似的代码来获得1分钟的背景时间,或者10到180秒之间的其他值吗?
答
一旦完成后台处理,您应该致电endBackgroundTask:
。如果您在分配给您的3分钟时间之前完成,那应该尽快结束后台处理,并让iOS暂停您的工作。我没有测试它来验证,但是这正是文档所暗示的。
+0
那么在这段时间里我还有其他进程正在运行。即使我手动杀死这个任务,该应用仍然清醒。 1分钟后我需要睡觉整个应用程序 – RDSpinz
您无法控制剩余的背景剩余时间。您只能开始/结束后台任务。有时180秒可以延长,我无法复制它,但这是随机发生的。 – Vasanth