现在的位置: 首页 > 综合 > 正文

ios应用在后台运行时间讨论

2018年02月14日 ⁄ 综合 ⁄ 共 2422字 ⁄ 字号 评论关闭

1. ios7系统中, 如果应用进入后台时,它并没有彻底进入后台, 而是有默认的10秒运行时间, 

代码如下, 把下面这部分代码放入在ios中, 点击某个按钮来调用, 然后按Home键进入后台, 观察log输出情况, (注:需要在release版下观察, debug版下程序不会停止,即使剩余时间为0也会继续运行。)

下面的代码会输出程序进入后台前的剩余时间长度

- (void)printLogs {

   
while (1) {

        NSLog(@"hello, world, last time=%f", [[UIApplication
sharedApplication] backgroundTimeRemaining]);

       
sleep(1);

    }

}

当程序在前台时,这个剩余时间是一个无效值。 

179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000

当按下Home键后, 才会正常输出。
last time=4.541742
2. 如果有些任务,比如一个下载或上传任务在程序进入后台后,仍然需要继续下载或上传任务, 苹果已经考虑到这点提供了一个启用后台运行的方式,可以使应用即使进入后台也能继续把该任务完成,(限制在180秒之内,超过后,系统会毫不留情地杀掉应用)
下面这个宏定义出的可以使用于所有ios版本中,只不过在iphone4之前, 这两个宏什么都不做。

#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_4_0

#define NABStartBackgroundTask() NSLog(@"NABStartBackgroundTask");\

UIBackgroundTaskIdentifier taskID = UIBackgroundTaskInvalid; \

taskID = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ \

NSLog(@"Expirationed Handler invoked.");\

[[UIApplication sharedApplication] endBackgroundTask:taskID]; }];

#define NABEndBackgroundTask() NSLog(@"NABEndBackgroundTask");\

[[UIApplication sharedApplication] endBackgroundTask:taskID];

#else

#define NABStartBackgroundTask()

#define NABEndBackgroundTask()

#endif

使用该宏能简化操作. 
使用时, 只需要在开始后台任务前调用
NABStartBackgroundTask()
在任务结束或者任务失败时调用, 如果下载或者上传结束, 也即任务结束后当然还是主动终止后台的运行以把资源调用还给系统。
NABEndBackgroundTask()
以终止后台180秒的运行。
3. 当后台的运行时候到达后,如果任务还没有结束,则会被系统无情地杀掉, 见下面的system log信息:
Sep  2 17:37:38 Red5c backboardd[28] <Warning>: UOgfd[831] has active assertions beyond permitted time: 
{(
   <BKProcessAssertion: 0x17697d30> identifier: Suspending process: UOgfd[831] permittedBackgroundDuration: 10.000000 reason: suspend owner pid:28 preventSuspend  preventThrottleDownCPU  preventThrottleDownUI  preventSuspendOnSleep 
)}
Sep  2 17:37:38 Red5c backboardd[28] <Warning>: Forcing crash report of UOgfd[831]...
Sep  2 17:37:38 Red5c backboardd[28] <Warning>: Finished crash reporting.
Sep  2 17:37:38 Red5c com.apple.launchd[1] (UIKitApplication:com.baidu.UOgfd[0x5df4][831]) <Notice>: (UIKitApplication:com.baidu.UOgfd[0x5df4]) Exited: Killed: 9
Sep  2 17:37:38 Red5c backboardd[28] <Warning>: Application 'UIKitApplication:com.baidu.UOgfd[0x5df4]' exited abnormally with signal 9: Killed: 9
4. 通过上面BeginBackgroundTask方法使应用在后台运行时, 若用户直接kill掉应用, 但应用仍然会继续运行,直到时间耗尽或是任务完成或失败去主动调用EndBackgoundTask.

抱歉!评论已关闭.