gpt4 book ai didi

ios - beginBackgroundTaskWithExpirationHandler 调用 endBackgroundTask 但没有结束进程

转载 作者:可可西里 更新时间:2023-11-01 03:28:01 26 4
gpt4 key购买 nike

我有一些长时间运行的进程,即使应用程序进入后台我也想运行。我正在调用应用程序的 beginBackgroundTaskWithExpirationHandler: 方法,并在 expirationBlock 中调用应用程序的 endBackgroundTask。这是实现:

__block UIBackgroundTaskIdentifier task = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[[UIApplication sharedApplication] endBackgroundTask:task];
task = UIBackgroundTaskInvalid;
}];
dispatch_queue_t queue = dispatch_queue_create("com.test.test1234", DISPATCH_QUEUE_SERIAL);
dispatch_async(queue, ^{
// My Task goes here
});

在某些情况下,我的串行队列有更多任务要执行,无法在系统提供的时间内完成。因此过期 block 将执行,并且我将结束 UIBackgroundTaskIdentifier 但不会停止调度过程(我什至无法取消调度)。

Apple 的文件说:

Each call to the beginBackgroundTaskWithName:expirationHandler: or beginBackgroundTaskWithExpirationHandler: method generates a unique token to associate with the corresponding task. When your app completes a task, it must call the endBackgroundTask: method with the corresponding token to let the system know that the task is complete. Failure to call the endBackgroundTask: method for a background task will result in the termination of your app. If you provided an expiration handler when starting the task, the system calls that handler and gives you one last chance to end the task and avoid termination.

因此,根据这个,如果我不调用 endBackgroundTask:,我的应用程序将被终止,这没关系。

我的问题是:在我当前的实现中,如果我在 expirationHandler block 中调用 endBackgroundTask: 并且我的调度队列的任务没有完成怎么办?我的应用将被终止或暂停?

谢谢

最佳答案

这里有一些场景,您需要在使用 beginBackgroundTaskWithExpirationHandler 时处理这些场景,否则您的应用将终止

场景 1:您的应用正在前台 中运行。您正在启动 beginBackgroundTaskWithExpirationHandler 然后进入 Background 模式。您的应用可以长期存活。

场景 2:您的应用正在前台 中运行。您正在启动 beginBackgroundTaskWithExpirationHandler 然后进入 Background 模式。然后返回到 Foreground 模式并且您没有调用 endBackgroundTask 那么您的应用程序仍然 execute background queue 因此它将扩展该进程以用于下一个 3分钟(IOS 7引入后,IOS 7之前,进程执行时间为10分钟)。所以必须取消后台队列,任务从后台队列出来,进入前台队列

下面是向您展示的代码。处理后台进程的最佳方式是什么。

第 1 步:声明 __block UIBackgroundTaskIdentifier bgTask 为全局变量。

第 2 步:在 applicationDidEnterBackground 中添加以下代码。

- (void)applicationDidEnterBackground:(UIApplication *)application {

bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
bgTask = UIBackgroundTaskInvalid;
}];

}

第 3 步:应用进入前台模式后停止后台任务处理程序。

- (void)applicationWillEnterForeground:(UIApplication *)application {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.

[[UIApplication sharedApplication] endBackgroundTask:bgTask];

}

关于ios - beginBackgroundTaskWithExpirationHandler 调用 endBackgroundTask 但没有结束进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29919573/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com