2013-07-10 99 views
1

当应用程序进入后台时,我有代码使计时器无效,但是当我按下主页按钮等待并打开应用程序时,计时器不停地继续运行。当应用程序进入后台时使计时器无效

我的计时器代码:

-(void) updateTimer { 

NSDate *currentDate = [NSDate date]; 
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate]; 
second = (NSUInteger)round(timeInterval); 
NSString *string = [NSString stringWithFormat:@"%02u:%02u:%02u", 
        second/3600, (second/60) % 60, second % 60]; 
hhmmssLabel.text = string; 
pauseTimeInterval = timeInterval; 


} 
-(void)pauseTimer { 

[tickerTimer invalidate]; 
tickerTimer = nil; 
} 

-(void) unPauseTimer { 

startDate = [NSDate date] ; 
startDate = [startDate dateByAddingTimeInterval:((-1)*(pauseTimeInterval))]; 
tickerTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/1.0 target:self selector:@selector(updateTimer) userInfo:nil repeats:YES]; 


} 

和我的代码,看看如果应用程序留下的前景

- (void)applicationWillResignActive:(UIApplication *)application 
{ 
if([tickerTimer isValid] && scoringBegan == YES){ 
[self pauseTimer]; 
scoringBegan = NO; 
[phonePos invalidate]; 
[baseReset invalidate]; 
    } 
} 

- (void)applicationDidEnterBackground:(UIApplication *)application 

    { 

    if([tickerTimer isValid] && scoringBegan == YES){ 
     [self pauseTimer]; 
     scoringBegan = NO; 
     [phonePos invalidate]; 
     [baseReset invalidate]; 


     } 
    } 
- (void)applicationWillTerminate:(UIApplication *)application 
{ 

    if([tickerTimer isValid] && scoringBegan == YES){ 
     [self pauseTimer]; 
     scoringBegan = NO; 
     [phonePos invalidate]; 
     [baseReset invalidate]; 
    } 
} 

****UPDATE* ** * * 当用户进入某个特定速度时,计时器会恢复,如果我错了但是位置服务仍然在后台工作,请纠正我的错误。所以定时器在暂停后自动恢复。那么有没有办法暂停位置服务?

回答

2

位置更新只在后台运行,如果您已将标志"App Registers for Location Updates"置于您的plist内。删除该标志,您将无法在后台更新。至于你的计时器,我只是记录它进入背景的布尔。然后,当您收到applicationWillEnterForeground通知时,如果布尔值正确,则可以使该计时器无效(因为它不会在后台继续增加)。

或者,您可以拨打beginBackgroundTaskWithExpirationHandler:并清理您的计时器,并暂停其他几秒钟。

是的,你可以通过调用stopUpdatingLocationstopMonitoringSignificantLocationChanges ..或任何适用于您的位置更新类型

+0

我使用[CLController.locMgr stopUpdatingLocation]暂停位置更新;现在我只需要测试它谢谢 – inVINCEable

+0

今天早上我测试了它,它完美的工作:)再次感谢 – inVINCEable

相关问题