iOS如何使用beginBackgroundTaskWithExpirationHandler执行任务

时间:2012-07-06 14:21:01

标签: ios multithreading ios5 multitasking

我正在尝试为简单的测试应用做两件事。

我一直在努力学习如何使用beginBackgroundTaskWithExpirationHandler

我想在用户按下主页按钮时执行backgroundTask(没什么特别的)。在9分钟内,我想提醒用户时间即将到期(如果可能),并允许用户切换回应用程序以续订10分钟。

我不需要向后兼容iOS 3或4。

2 个答案:

答案 0 :(得分:3)

如果您希望代码在后台继续,那么您需要将其包装在后台任务中。完成后调用endBackgroundTask也非常重要 - 否则应用程序将在分配的时间到期后被杀死

- (IBAction) buttonPressed: (id) sender

        [self beingBackgroundUpdateTask];

        // Do your long running background thing here

        [self endBackgroundUpdateTask];
    });
}
- (void) beingBackgroundUpdateTask
{
    self.backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        [self endBackgroundUpdateTask];
    }];
}

- (void) endBackgroundUpdateTask
{
    [[UIApplication sharedApplication] endBackgroundTask: self.backgroundUpdateTask];
    self.backgroundUpdateTask = UIBackgroundTaskInvalid;
}

答案 1 :(得分:1)

将代码放入applicationDidEnterBackground的{​​{1}}功能中。您需要设置UIApplicationDelegate并安排它。你也应该在UILocalNotification中禁用它,这样就不会触发用户在应用程序到期之前返回应用程序。

applicationWillEnterForeground

我在那里取消的代码实际上会取消所有通知。如果您有多个通知并且只想取消特定通知,则应在设置时为通知的- (void)applicationDidEnterBackground:(UIApplication *)application { UILocalNotification *timerNotification = [[UILocalNotification alloc] init]; //set up notification with proper time and attributes [[UIApplication sharedApplication] scheduleLocalNotification:timerNotification]; } - (void)applicationWillEnterForeground:(UIApplication *)application { [[UIApplication sharedApplication] cancelAllLocalNotifications]; } 属性指定密钥/值。然后,当应用程序进入前台时,通过执行

获取所有活动通知的列表

userInfo

并循环浏览它们,检查NSArray *notifications = [[UIApplication sharedApplication] scheduledLocalNotifications];直到找到你想要的那个,然后用

取消那个

userInfo