我在我的cocos2d-x游戏(c ++)ios中使用了一个计时器。我使用的是cocos2d-x 2.2版本。 我的时间功能如下 在我的初学者
this->schedule(schedule_selector(HelloWorld::UpdateTimer), 1);
我已将该功能定义如下。
void HelloWorld::UpdateTimer(float dt)
{
if(seconds<=0)
{
CCLOG("clock stopped");
CCString *str=CCString::createWithFormat("%d",seconds);
timer->setString(str->getCString());
this->unschedule(schedule_selector(HelloWorld::UpdateTimer));
}
else
{
CCString *str=CCString::createWithFormat("%d",seconds);
timer->setString(str->getCString());
seconds--;
}
}
Everythings工作正常。但即使游戏进入后台状态,我也有这个计时器继续运行。我试过在appdelegate中评论didEnter Background的主体,但没有成功。任何帮助将不胜感激 感谢
答案 0 :(得分:0)
如果应用程序进入后台,除了一些特殊的后台线程外,没有其他线程被执行。 最好的方法是在didEnterBackground期间将unix时间戳保存在变量中,当应用程序恢复时,获取当前的unix时间戳并比较delta,以获得通过的总时间并相应地更新计时器。
答案 1 :(得分:0)
在我的AppDelegate.cpp中,我在applicationDidEnterBackground函数中编写了以下代码。每当应用程序进入后台并将其存储在CCUserdefault密钥中时,我会以秒为单位获取时间值。当应用程序到达前台时,我再次使用本地系统时间并从我存储在密钥中的时间中减去该时间。以下是我的代码
void AppDelegate::applicationDidEnterBackground()
{
time_t rawtime;
struct tm * timeinfo;
time (&rawtime);
timeinfo = localtime (&rawtime);
CCLog("year------->%04d",timeinfo->tm_year+1900);
CCLog("month------->%02d",timeinfo->tm_mon+1);
CCLog("day------->%02d",timeinfo->tm_mday);
CCLog("hour------->%02d",timeinfo->tm_hour);
CCLog("minutes------->%02d",timeinfo->tm_min);
CCLog("seconds------->%02d",timeinfo->tm_sec);
int time_in_seconds=(timeinfo->tm_hour*60)+(timeinfo->tm_min*60)+timeinfo->tm_sec;
CCLOG("time in seconds is %d",time_in_seconds);
CCUserDefault *def=CCUserDefault::sharedUserDefault();
def->setIntegerForKey("time_from_background", time_in_seconds);
CCDirector::sharedDirector()->stopAnimation();
// if you use SimpleAudioEngine, it must be pause
// SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic();
}
void AppDelegate::applicationWillEnterForeground()
{
CCUserDefault *def=CCUserDefault::sharedUserDefault();
int time1=def->getIntegerForKey("time_from_background");
time_t rawtime;
struct tm * timeinfo;
time(&rawtime);
timeinfo = localtime (&rawtime);
CCLog("year------->%04d",timeinfo->tm_year+1900);
CCLog("month------->%02d",timeinfo->tm_mon+1);
CCLog("day------->%02d",timeinfo->tm_mday);
CCLog("hour------->%02d",timeinfo->tm_hour);
CCLog("mintus------->%02d",timeinfo->tm_min);
CCLog("seconds------->%02d",timeinfo->tm_sec);
int time_in_seconds=(timeinfo->tm_hour*60)+(timeinfo->tm_min*60)+timeinfo->tm_sec;
int resume_seconds= time_in_seconds-time1;
CCLOG("app after seconds == %d", resume_seconds);
CCDirector::sharedDirector()->startAnimation();
// if you use SimpleAudioEngine, it must resume here
// SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic();
}
您可以查看并计算应用留在后台的时间。