iOS开发之后台运行调用beginBackgroundTaskWithExpirationHandler

APP在正常运行过程中,突然按下Home键或者锁屏键,也或者电话接入,APP将进入后台,在几秒钟以后将退出程序.在程序使用socket或者播放器连接,短暂的进入后台需要保持活动状态,以免播放器退出,socket断开,可调用系统的beginBackgroundTaskWithExpirationHandler方法,程序进入后台AppDelegate将会使用applicationDidEnterBackground:方法,只需要在这里告诉即可.如下面
 backTaskIdentifier = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
         [[UIApplication sharedApplication] endBackgroundTask:backTaskIdentifier];
         backTaskIdentifier = UIBackgroundTaskInvalid;
     }];
使用beginBackgroundTaskWithExpirationHandler必须要成对使用endBackgroundTask方法,因为在后台保持任务只能持续180秒的时间,可以使用[[UIApplication sharedApplication]backgroundTimeRemaining]获取到当前在后台的剩余时间.超过180秒,不能调用当前的ID(即backTaskIdentifier)的endBackgroundTask,APP将崩溃闪退,这是Apple强制APP退出活动的结果.
 
如果在回调中不调用endBackgroundTask,则后台运行一直存在。

posted on 2018-05-10 11:41  爬上墙头 = 红杏  阅读(245)  评论(0)    收藏  举报