定时器:如何在后台保持定时器活动

3
在我的 iPhone 定时器应用中,需要在后台运行定时器。因此,在 appdelegate 中设置了通知并且工作得非常完美...通过从视图控制器中调用方法来保持计时器活动状态。
以下是一些代码...
App delegate
- (void)applicationDidEnterBackground:(UIApplication *)application
{
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
     */

    NSLog(@"Time Remaining %d",(self.viewController.totalSeconds-self.viewController.totalCount));
    [self.viewController selectandnotify:(self.viewController.totalSeconds-self.viewController.totalCount)];
    [self.viewController stopTimer];
    [self.viewController startTimerAction];

}

我在这里调用了我的视图控制器中的 startTimerAction 方法...看一下...

-(void)startTimerAction
{
 timer_main = [NSTimer scheduledTimerWithTimeInterval:(1.0) target:self    selector:@selector(ShowActicity) userInfo:nil repeats:YES];
}

NSTimer是什么?

每次执行时,ShowActivity方法将在下面的视图控制器中调用。

-(void)ShowActicity
{

    NSLog(@"Total Counts %d",totalCount);
    if (totalCount == totalSeconds) {
        if ([timer_main isValid]) {
            [timer_main invalidate];
            isTimeOver = YES;
            [self generateLog];
        }
    } else {
        totalCount++;

        seconds =seconds + 1;
        if(seconds > 59)
        {
            minutes = minutes + 1;
            seconds= 0;
        }

如何从视图控制器中每次调用此方法...

  • 我如何从appdelegate中每次调用showActivity方法...

    • 我应该使用代理吗?

    • 我应该在我的Appdelegate中创建showActivity和定时器吗?

  • 实际上,我希望此应用程序在应用程序中的视图切换时运行...

我认为使用代理是一个不错的选择?

还有其他方法...请提供一些建议

1个回答

4

通常情况下,使用此代码进行后台运行。在后台计时器不起作用。

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    UIApplication*    app = [UIApplication sharedApplication];

    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        [app endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    }];

    // Start the long-running task and return immediately.
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        // Do the work associated with the task.
        [self startTimerAction];
        [app endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    });
}

http://developer.apple.com/library/ios/#DOCUMENTATION/iPhone/Conceptual/iPhoneOSProgrammingGuide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html#//apple_ref/doc/uid/TP40007072-CH4-SW3


谢谢Sachin,这是一个很好的答案,我的问题完美地解决了...再次感谢... - Arpit B Parekh
抱歉晚了,bgTask 是 UIBackgroundTaskIdentifier 类型。 - Tendulkar
@Tendulkar,您能否请看一下:http://stackoverflow.com/questions/30635723/call-a-method-with-delay-of-15-sec-irrespective-of-app-state/30635938#30635938 - iYoung

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接