当应用程序进入后台时,我有代码使计时器无效,但是当我按下主页按钮等待并重新打开应用程序时,计时器会持续整个时间而不会停止。
我的计时器代码:
-(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];
}
}
****更新* ** **当 用户以一定的速度行驶时,计时器会恢复,如果我错了,请纠正我,但位置服务仍在后台工作。所以定时器在暂停后会自动恢复。那么有没有办法暂停定位服务呢?