摘录自 http://jingyan.baidu.com/article/f54ae2fcdf75bf1e92b84913.html 以及 https://i-blog.csdnimg.cn/blog_migrate/af5c94199379808bf1bbed47b4c3aa8f.png
AppDelegate继承自Application类,是cocos2d-x平台的入口程序。
一般地,这个类主要处理三个事件:
系统平台的窗口创建完成;
系统通平台的窗口被盖住将进入后台运行;
系统平台的窗口恢复到前台;
这三个事件分别对应了AppDelegate中的三个个方法
virtual bool applicationDidFinishLaunching();
virtual void applicationDidEnterBackground();
virtual void applicationWillEnterForeground();
使用这个类的方式(cocos2d-x3.8),首先在main函数里定义AppDelegate类的对象,然后调用Appdelegate类的函数 getInstance()->run()进入程序的主逻辑,至于后面是执行 上述三个事件的哪一个这需要看程序的默认设定以及使用者给出的响应。
当android,ios平台来电话,就会有新窗口盖住当前窗口,applicationDidEnterBackground就会被调用
当windows,mac平台最小化,applicationDidEnterBackground就会被调用
一般在这个方法中处理:
让所有的屏幕动作停下来
让所有的音乐和音效停下来
(有时候要保存当前游戏状态持久化到磁盘)
applicationWillEnterForeground中处理
让所有屏幕动作继续
让有音乐和音效继续
(恢复用户数据)
详细的代码 转自 https://i-blog.csdnimg.cn/blog_migrate/af5c94199379808bf1bbed47b4c3aa8f.png
AppDelegate::AppDelegate() { //1,构造AppDelegate
}
AppDelegate::~AppDelegate()
{
}
bool AppDelegate::applicationDidFinishLaunching() {//3,在2初始化完之后进入,结束初始化appDelegate
// initialize director
CCDirector* pDirector = CCDirector::sharedDirector();
CCEGLView* pEGLView = CCEGLView::sharedOpenGLView();
pDirector->setOpenGLView(pEGLView);
// turn on display FPS
pDirector->setDisplayStats(true);
// set FPS. the default value is 1.0/60 if you don't call this
pDirector->setAnimationInterval(1.0 / 60);
CCScene * pScene = CCScene::create();
GameDemoManager * pLayer = new GameDemoManager();
pLayer->initGame();
pLayer->autorelease();
pScene->addChild(pLayer);
pDirector->runWithScene(pScene);
return true;
}
// This function will be called when the app is inactive. When comes a phone call,it's be invoked too
void AppDelegate::applicationDidEnterBackground() {//4,当手机处于后台运行的时候,进入该处
CCDirector::sharedDirector()->stopAnimation();
// if you use SimpleAudioEngine, it must be pause
// SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic();
}
// this function will be called when the app is active again
void AppDelegate::applicationWillEnterForeground() { /,2,构造完了AppDelegate之后进入初始化application
CCDirector::sharedDirector()->startAnimation();
// if you use SimpleAudioEngine, it must resume here
// SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic();
}
从上面分析:
AppDelegate其实就是整个程序的入口,它的初始化步骤就是上面的1-3,4则是在手机后台运行该程序时所调用的