【问题标题】:destroy background timer in foreground在前台销毁后台计时器
【发布时间】:2014-05-14 12:31:44
【问题描述】:

我是 ios 的新手。我正在做一个应用程序,我必须在后台计算时间,但我的问题是时间不会在前台停止。请告诉我如何在前台停止后台计时器? 非常感谢。

【问题讨论】:

  • 请显示您正在使用的代码。你的意思是当应用在后台时(暂停)?
  • NSTimer *timer = [NSTimer timerWithTimeInterval:5 target:weakSelf selector:@selector(timerDidFire:) userInfo:nil repeats:NO];
  • 请说明前景的含义。如果有后台,则意味着您的应用程序已暂停,而不是 Timer 也已暂停
  • 正如 Argent 指出的那样,计时器不会在后台触发。如果您在后台每五秒触发一次计时器,您将损坏电池。你真正想要完成什么?也许有一些方法可以使用 applicationWillEnterForeground 和 applicationWillEnterBackground。

标签: objective-c ios7 nstimer background-foreground


【解决方案1】:

要在同一类的某处停止计时器:

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

[Timer invalidate];
    Timer = nil;
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    NSLog(@"Background process is Start(EnterBackground)!");
    __block UIBackgroundTaskIdentifier bgTask ;
    UIApplication  *app = [UIApplication sharedApplication];
    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        [app endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    }];
    Timer = [NSTimer scheduledTimerWithTimeInterval:4.0f target:self  selector:@selector(process)  userInfo:nil repeats:YES];
}

【讨论】:

  • 你能告诉我应该在哪里介绍“定时器”吗?
  • 在 Appdelegate.h 中声明 NSTimer *Timer;
  • 报错--"undeclare identifier"timer"。如何解决?
【解决方案2】:

一般来说,不要使用计时器。使用NSDate 存储您感兴趣的开始时间(例如应用程序进入后台),然后将该日期与[NSDate date](即当前日期)进行比较,以查看已经过去了多少时间。

当应用程序在后台运行时,确实没有充分的理由运行计时器。

【讨论】:

    猜你喜欢
    • 2015-05-16
    • 1970-01-01
    • 2021-01-04
    • 2014-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多