iOS申請延長進入後臺代碼片段

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之後採用異步調用該線程將暫停等到程序進入前臺接着運行,如果是直接在主線程調用將一直運行到任務完成,即使進入前臺也會柱塞到該任務完成;

有哪位高人可以幫忙解釋一下,謝謝~~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章