注:原文也在公司内部论坛上发了
本文通过分析cocos2d-x(分析版本为cocos2d-x-2.2.1)自身提供的示例程序HelloLua(在目录$(sourcedir)\samples\Lua\HelloLua\下)来分析cocos2d-x的在android平台下的具体启动过程。
我们知道android平台的游戏是从一个Activity开始的。HelloLua的启动Activity是在文件HelloLua.java中定义的,相关代码如下:
public class HelloLua extends Cocos2dxActivity{
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
public Cocos2dxGLSurfaceView onCreateGLSurfaceView() {
return new LuaGLSurfaceView(this);
}
static {
System.loadLibrary("hellolua");
}
}
从上面的代码,启动Activity是继承Cocos2dxActivity的,在游戏启动时,Activity首先会执行静态代码块,加载libhellolua.so库,这个动态链接库是在用NDK编译的时候生成的;然后就是执行onCreate方法,这里调用了父类Cocos2dxActivity的onCreate方法。 Cocos2dxActivity在
$(sourcedir)\cocos2dx\platform\android\java\src\org\cocos2dx\lib\Cocos2dxActivity.java
中定义,其OnCreate方法代码如下:
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sContext = this;
this.mHandler = new Cocos2dxHandler(this);
this.init();
Cocos2dxHelper.init(this, this);
}
这里主要是执行初始化过程,Cocos2dxHandler主要处理显示Dialog的消息,Cocos2dxHelper是个辅助类,我们主要看init()方法,代码如下:
public void init() {
// FrameLayout
ViewGroup.LayoutParams framelayout_params =
new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT);
FrameLayout framelayout = new F