iOS申请延长进入后台代码片段

来源:互联网 发布:手机淘宝彩票怎么买 编辑:程序博客网 时间:2024/05/21 14:03
void runTaskInBackground(void (^taskBlock)(void), void (^timeOutBlock)(void), BOOL aSync){    __block UIBackgroundTaskIdentifier taskId = 0;    taskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^    {        if (NULL != timeOutBlock)        {            timeOutBlock();        }        [[UIApplication sharedApplication] endBackgroundTask:taskId];        taskId = UIBackgroundTaskInvalid;        ATGLog(@"Timeout, background task has be ended");    }];        if (UIBackgroundTaskInvalid != taskId)    {        if (aSync && [UIDevice currentDevice].multitaskingSupported)        {            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^            {                if (NULL != taskBlock)                {                    ATGLog(@"starting run background task in multi-thread:%@, remain time:%f", [NSThread currentThread],                           [UIApplication sharedApplication].backgroundTimeRemaining);                    taskBlock();                    [[UIApplication sharedApplication] endBackgroundTask:taskId];                    taskId = UIBackgroundTaskInvalid;                    ATGLog(@"finished background task in multi-thread:%@, remain time:%f", [NSThread currentThread],                           [UIApplication sharedApplication].backgroundTimeRemaining);                }            });        }        else        {            if (NULL != taskBlock)            {                ATGLog(@"starting run background task in single-thread:%@, remain time:%f", [NSThread currentThread],                       [UIApplication sharedApplication].backgroundTimeRemaining);                taskBlock();                [[UIApplication sharedApplication] endBackgroundTask:taskId];                taskId = UIBackgroundTaskInvalid;                ATGLog(@"finished background task in single-thread:%@, remain time:%f", [NSThread currentThread],                       [UIApplication sharedApplication].backgroundTimeRemaining);            }        }    }}

通过测试,发现无论在iOS6和iOS7上出现与SDK描述不符的现象,情况如下:

1、调用beginBackgroundTaskWithExpirationHandler之后,就算超时(iOS6 600S iOS7 180S)或者调用endBackgroundTask之后,app其它线程依然正常运行没有被杀死(注:该线程有日志打印和文件操作);

2、调用beginBackgroundTaskWithExpirationHandler之后,超时(iOS6 600S iOS7 180S)之后,如果beginBackgroundTaskWithExpirationHandler之后采用异步调用该线程将暂停等到程序进入前台接着运行,如果是直接在主线程调用将一直运行到任务完成,即使进入前台也会柱塞到该任务完成;

有哪位高人可以帮忙解释一下,谢谢~~

0 0