//创建通知监听(判断游戏时长)
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:nil]; //监听是否触发home键挂起程序.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive:) name:UIApplicationDidBecomeActiveNotification object:nil]; //监听是否重新进入程序程序.#pragma mark - 实现2个NSNotificationCenter所触发的事件方法
//回到后台都视为一次会话结束(计时end)
+ (void)applicationWillResignActive:(NSNotification *)notification
{
NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
long long int date = (long long int)time;
NSString * timeStr = [NSString stringWithFormat:@"%lld",date];
NSLog(@"后台:timestr :%@ ",timeStr);
}
//回到前台都视为一次新启动(计时start)
+ (void)applicationDidBecomeActive:(NSNotification *)notification
{
NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
long long int date = (long long int)time;
NSString * timeStr = [NSString stringWithFormat:@"%lld",date];
NSLog(@"前台:timestr :%@ ",timeStr);
}
再将两个时间相减可得出游戏时长。
本文介绍了一种通过监听应用程序状态变化来记录游戏时长的方法。具体实现为:使用NSNotification监听应用从前台转到后台的时间点作为游戏结束时间,并记录;同样地,监听应用从后台返回前台的时间点作为游戏开始时间,并记录。通过计算前后时间差得出游戏时长。
504

被折叠的 条评论
为什么被折叠?



