【问题标题】:How to run the timer in background of the application?如何在应用程序的后台运行计时器?
【发布时间】:2012-10-06 16:00:36
【问题描述】:

我想减少倒计时。因此,如果用户最小化应用程序,则应用程序加载背景。如何在应用程序后台运行计时器?我正在使用下面的代码。当应用程序最小化时,计时器停止。请帮帮我。

        timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerCountDown) userInfo:nil repeats:YES];

- (void)timerCountDown
{
    if(secondsLeft > 0 ) {
        secondsLeft -- ;
        hours = secondsLeft / 3600;
        minutes = (secondsLeft % 3600) / 60;
        seconds = (secondsLeft %3600) % 60;
    }
}

【问题讨论】:

标签: iphone


【解决方案1】:

应用程序不会永远在后台运行;你不能保证当应用关闭时计时器会继续。

在应用程序委托中,在 applicationDidEnterBackground 中,保存任何允许计时器在 applicationWillEnterForeground 时继续运行的数据。在您的特定情况下,使后台计时器无效,并在进入前台时再次启动它。使用您的 secondsLeft,您可能希望能够通过 NSDates 的差异来计算它,并保存开始和结束日期。

【讨论】:

    【解决方案2】:

    我得到了答案,它工作得很好。

    UIBackgroundTaskIdentifier bgTask =0;
    UIApplication  *app = [UIApplication sharedApplication];
    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        [app endBackgroundTask:bgTask];
    }];
    
    timer = [NSTimer
                   scheduledTimerWithTimeInterval:1.0
                   target:self
                   selector:@selector(timerCountDown:)
                   userInfo:nil
                   repeats:YES];
    

    【讨论】:

    • +1 谢谢。有用。但请尝试添加对代码的解释,以便用户了解代码 sn-p 的实际作用。
    • @Mani 它就像一个魅力,但它是一个健康的解决方案吗?
    • 是的。我被这样使用并发布了应用程序。它在应用商店中运行良好。
    • 我猜定时器会在一定的时间间隔(主要是 3 分钟)后停止,因为 'endBackgroundTask' 被调用。
    猜你喜欢
    • 1970-01-01
    • 2014-12-11
    • 2015-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-16
    相关资源
    最近更新 更多