Thursday, May 31, 2012

cocos2d-x resume from background issue...


I love cocos2d-x, it helps me to write games quickly on iOS and android with just one code base.

But I found a small problem that if my cocos2d-x games run into background, and when it get back to foreground, it will restart !

That means if you play my game for a while and a phone call just received, after you pick up the call, you will need to re-play the game from the very first stage.

That's bad, and I don't like it !

After a while googling, I found the solution, and I post here to make sure if someone have the same issue with me, and you can try this solution, it works for me, and maybe you too !

Step1 : open the AppDelegate.cpp

Step2 : make your code like below


// This function will be called when the app is inactive. When comes a phone call,it's be invoked too
void AppDelegate::applicationDidEnterBackground()
{
    CCDirector::sharedDirector()->stopAnimation();
    CCDirector::sharedDirector()->pause();

// if you use SimpleAudioEngine, it must be pause
CocosDenshion::SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic();
}

// this function will be called when the app is active again
void AppDelegate::applicationWillEnterForeground()
{
    CCDirector::sharedDirector()->stopAnimation();
    CCDirector::sharedDirector()->resume();
    CCDirector::sharedDirector()->startAnimation();

// if you use SimpleAudioEngine, it must resume here
CocosDenshion::SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic();
}

Step3 : re-compile and run it

And that's all !!!

Hope you will enjoy your coding time !!!

2 comments:

  1. why do you have to stopAnimation and then pause? shouldn't it be only one of these?

    ReplyDelete
  2. Sorry, but my phone is not stopped when i play cocos 2dx game app.

    it is not called "void AppDelegate::applicationDidEnterBackground()"
    please help me!

    ReplyDelete