人猿星球

关于如何在进入后台后继续运行

2016-07-13  本文已影响502人  这位网友

由于修改Bug,需要用到这个,暂时找的一些资料,未做整理。
Bug是要让NSTimer在进入后台之后继续计时

NSTimer后台运行并弹出提示

iOS程序进入后台后仍运行定时器NSTimer

ios之申请后台延时执行和做一个假后台的方法

对于以上方法,其实我看的有点晕。
而且由于同事说我们不能这样搞,所以就只好选用取巧,而又无伤大雅的方法。

思路就是记录即将失去活跃时的时间(进入后台),然后进入前台的时候再取一下当前时间,计算差值,更改需要显示的时间就行

具体方法就是:

在AppDelegate里边,进入后台和进入前台的时候发送通知

#pragma mark - 将要进入前台
- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // 通知
    [[NSNotificationCenter defaultCenter] postNotificationName:@"applicationWillEnterForegroundNotif" object:nil userInfo:nil];
}

#pragma mark - 将要失去活跃
- (void)applicationWillResignActive:(UIApplication *)application
{
    // 通知
    [[NSNotificationCenter defaultCenter] postNotificationName:@"applicationWillResignActiveNotif" object:nil userInfo:nil];
}

然后在对应的页面中注册通知

//添加通知,记录进入后台与进入前台的时间差
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillEnterForegroud) name:@"applicationWillEnterForegroundNotif" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive) name:@"applicationWillResignActiveNotif" object:nil];

实现通知方法

@property (nonatomic, assign) NSInteger nowTime;//每次退出的时候保存的时间
@property (nonatomic, assign) NSInteger howLong;//每次进入后台到进入前台的时间

#pragma mark - NSTimer要在进如后台之后继续运行
-(void)appWillEnterForegroud{
    NSLog(@"进入前台");
    NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:0];
    NSInteger nowTime = [date timeIntervalSinceNow];
    if (_nowTime != 0) {
        _howLong = _nowTime - nowTime; //得到从进入后台到进入前台所经过的时间
//        NSLog(@"howLong = %li",(long)_howLong);
        [self oneCureHowLong:(int)_howLong];//拿到所经过时间之后,自行处理
    }
}

-(void)applicationWillResignActive{
    NSLog(@"失去活跃");
    NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:0];
    NSInteger nowTime = [date timeIntervalSinceNow];
    _nowTime = nowTime;
}

补充:

其实NSTimer加入到NSRunLoop后,在后台也是运行的,只是在前台的时候才会执行刷新UI的操作,而在后台是不会的,只会执行计时等操作。所以在后台时能看到传输数据这些操作继续运行,但是打开页面才会看到UI上的时间Label开始计时。

就像我们经常需要注意并且去做的一样,把刷新UI的操作都放在主线程中进行。

上一篇 下一篇

猜你喜欢

热点阅读