NSTimer 锁屏以及进入后台不调用的解决方案

来源:互联网 发布:qq聊天记录软件 编辑:程序博客网 时间:2024/05/18 01:10

在开发中遇到一个问题,我们有一个如图所示的计时器:

     在实际测试过程中发现,计时器只在程序active时工作,进入后台或者锁屏后就不工作,时间就会“暂停”住。仔细一想,NSTimer实际上就是一个新线程,当程序进入后台时,这个线程就被挂起不工作,当然计时器就会被“暂停”。

        为了解决这个问题,我找到了一个方法,能解决这个问题,但不一定是最佳方案。


首先,我们要明白进入后台或者锁屏后调用的方法。

//AppDelegate.m文件- (void)applicationWillResignActive:(UIApplication *)application- (void)applicationDidEnterBackground:(UIApplication *)application

相对应,从后台进入程序,或者解除锁屏后调用的方法为:

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



解决问题方案:当程序进入后台时,发送通知并记录当前时间;当从后台进入程序时,发送通知并根据两次时间差更新定时器。

代码如下:

AppDelegate:

#define NOTIFICATION_RESIGN_ACTIVE              @"appResignActive"#define NOTIFICATION_BECOME_ACTIVE              @"appBecomeActive"- (void)applicationWillResignActive:(UIApplication *)application{//进入后台时调用      [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_RESIGN_ACTIVE object:nil];}- (void)applicationDidBecomeActive:(UIApplication *)application{//从后台进入程序时调用    [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_BECOME_ACTIVE object:nil];}


接受通知并更新计时器:

ViewController.m中:

NSDate *resignBackgroundDate;- (void)registerBackgoundNotification{    [[NSNotificationCenter defaultCenter] addObserver:self                                             selector:@selector(resignActiveToRecordState)                                                 name:NOTIFICATION_RESIGN_ACTIVE                                               object:nil];    [[NSNotificationCenter defaultCenter] addObserver:self                                             selector:@selector(becomeActiveToRecordState)                                                 name:NOTIFICATION_BECOME_ACTIVE                                               object:nil];}- (void)resignActiveToRecordState{    resignBackgroundDate = [NSDate date];}- (void)becomeActiveToRecordState{    NSTimeInterval timeHasGone = [[NSDate date] timeIntervalSinceDate:resignBackgroundDate];    timerCount = timeHasGone + timerCount;}

timeHasGone是进入后台与后台进入程序的时间差。全局变量timerCount是我们计时器需要显示的时间。

一旦重新进入程序,timer继续工作读取全局变量timerCount,计时恢复工作!



这里的代码有部分缺省,因为是从整个项目中抽取出来的片段。

定时器的定义和计时器的显示代码我都没有写上来,不过不影响整个代码的思路。

抛砖引玉,如果您有更好的方法请留在评论处。


PS:记得在dealloc中[[NSNotificationCenter defaultCenter] removeObserver:self];




0 0
原创粉丝点击