您的位置:首页 > 编程语言 > C语言/C++

如何用 纯C++(ndk)开发安卓应用 ?

2014-06-04 07:35 363 查看
视频教程请关注 http://edu.csdn.net/lecturer/lecturer_detail?lecturer_id=440
 如何安装安卓的开发环境以及怎么设置ndk的环境变量等在前边的文章已经有了详细的讲解,在这里我就不再说明,如果有不会安装和设置环境的,请先参考安卓环境搭建的内容。

  好,假设以及安装好了ndk,使用纯c++开发安卓程序,下边是详细的步骤与说明:

  1.编写入口函数

    android_main为入口函数,和C++中的main函数是一样的。这里创建CELLAndroidApp的对象,直接调用main函数。

void android_main(struct android_app* state)
{
CELLAndroidApp    app(state);

app.main(0,0);
}


 说明:其中的 CELLAndroidApp是我们设计的一个图形绘制类,稍后将对其做详细说明

2.绘制类的实现说明

  2.1类的成员说明

protected:
EGLConfig        _config;
EGLSurface       _surface;
EGLContext       _context;
EGLDisplay       _display;
android_app*     _app;
int              _width;
int              _height;


部分参数说明:

  _surface:用于绘制图形,相当于windows绘图中的位图

  _context:可以看做是opengl对象

  _display:用于绘图的设备上下文,类似于windows绘图中的dc

  2.2 构造函数说明  

CELLAndroidApp(android_app* app):_app(app)
{
_surface    =    0;
_context    =    0;
_display    =    0;
_width        =    64;
_height        =    48;
app->userData        =    this; //用户数据
app->onAppCmd         =     handle_cmd; //窗口的创建销毁等
app->onInputEvent     =    handle_input; //回调函数
}


  值得注意的是,这里的app中的userData,传入用户数据,这里直接传入this,onAppCmd传入的handle_cmd回调函数,onInputEvent传入的事handle_input回调函数

  2.3 类中函数main()说明

virtual    void     main(int argc,char** argv)
{
int ident;
int    events;
android_poll_source* source;

while (true)
{
while ((ident = ALooper_pollAll(0, NULL, &events, (void**)&source)) >= 0)
{
if (source != NULL)
source->process(_app, source); //有触摸事件,调用input函数,相当于dispatchmessage

if (_app->destroyRequested != 0)
return;
}
render();
}
}


  其中的android_poll_source相当于windows中的消息队列,用于存放消息,这个函数中模拟了windows中的消息机制。

  ALooper_pollAll()函数,用于获取消息。值得注意的是第一个参数,如果第一个参数传入0,则不等待,调用后直接返回,类似于windows消息机制中的pickMessage()函数,如果传入-1,则类似于windows消息机制中的SendMessage()函数。 返回值:如果返回值大于大于等于0表示获取到数据,如果为-1则表示失败,未获取到数据。

  其中发source如果不为空,则表示有触摸事件,则调用process()函数,相当于windows中调用dispatchMessage()函数。

  最后,调用render()函数,绘制图形。

  2.4 初始化设备函数initDevice()

virtual void     initDevice()
{
const EGLint attribs[] =
{
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_BLUE_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_RED_SIZE, 8,
EGL_NONE
};
EGLint     format;
EGLint    numConfigs;

_display    =    eglGetDisplay(EGL_DEFAULT_DISPLAY);

eglInitialize(_display, 0, 0);

eglChooseConfig(_display, attribs, &_config, 1, &numConfigs);

eglGetConfigAttrib(_display, _config, EGL_NATIVE_VISUAL_ID, &format);

ANativeWindow_setBuffersGeometry(_app->window, 0, 0, format);

_surface    =     eglCreateWindowSurface(_display, _config, _app->window, NULL);

#if 0
EGLint contextAtt[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE, EGL_NONE };

_context     =     eglCreateContext(_display, _config, 0, contextAtt);
#else
_context     =     eglCreateContext(_display, _config, 0, 0);
#endif

if (eglMakeCurrent(_display, _surface, _surface, _context) == EGL_FALSE)
{
LOGW("Unable to eglMakeCurrent");
return;
}

eglQuerySurface(_display, _surface, EGL_WIDTH, &_width);
eglQuerySurface(_display, _surface, EGL_HEIGHT, &_height);

onCreate();

// Initialize GL state.
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST);
glEnable(GL_CULL_FACE);
glShadeModel(GL_SMOOTH);
glDisable(GL_DEPTH_TEST);
glViewport(0,0,_width,_height);
glOrthof(0,_width,_height,0,-100,100);
}


  首先需要说明的是attribs数组,改数组中主要存储了绘制图形的一些属性信息,他们是成对出现的,如EGL_SURFACE_TYPE则表示绘制图形类型, EGL_WINDOW_BIT则表示绘制到窗口上。

  eglGetDisplay()函数:表示获取一个显示设备

  eglInitialize():表示初始化获取到的显示设备

  eglChooseConfig():绘制属性的配置

  eglGetConfigAttrib():设置绘制格式

  ANativeWindow_setBuffersGeometry():将格式应用到窗口

  eglCreateWindowSurface():创建绘图窗口

  eglCreateContext():创建opengl的绘图上下文

  eglMakeCurrent():绑定到绘图设备上下文

  eglQuerySurface():获取图片的宽度和高度,具体获取哪一个根据最后一个参数确定

  glHint()、glEnable()和glOrthof()等函数则是与绘图的投影相关的内容,包括初始化、设置模式等内容。

  2.5 绘制函数render()

virtual    void     render()
{
if(_display == 0)
{
return;
}
glClearColor(0,0,0, 1);
glClear(GL_COLOR_BUFFER_BIT);

glEnableClientState(GL_VERTEX_ARRAY);
if(g_arVertex.size() >= 2)
{
glColor4f(1,1,1,1);
glVertexPointer(3,GL_FLOAT,0,&g_arVertex[0]);
glDrawArrays(GL_LINE_STRIP,0,g_arVertex.size());
}

eglSwapBuffers(_display,_surface); //双缓存的交换缓冲区
}


  render()函数主要用于绘制点,对主要的几个函数做如下说明:

  glClearColor():用于将屏幕清为黑色

  glClear():清空颜色缓冲区

  glEnableClientState():启动定点数组

  glVertexPointer():制定定点缓冲区

  glDrawArrays():绘制点数组

  eglSwapBuffers():类似双缓存的交换缓冲区

  2.6 handle_cmd()函数

static void     handle_cmd(android_app* app, int32_t cmd)
{
CELLAndroidApp*    pThis    =    (CELLAndroidApp*)app->userData;
pThis->cmd(app,cmd);
}


  2.7 handle_input()函数

static void     handle_input(android_app* app, AInputEvent* event)
{
CELLAndroidApp*    pThis    =    (CELLAndroidApp*)app->userData;
pThis->input(app,event);
}


  2.8 input()函数

virtual    int     input(struct android_app* app, AInputEvent* event)
{
int32_t    evtType    =    AInputEvent_getType(event);
switch(evtType)
{
case AINPUT_EVENT_TYPE_KEY:
break;
case AINPUT_EVENT_TYPE_MOTION:
{
int32_t    sourceId    =     AInputEvent_getSource(event);
if(AINPUT_SOURCE_TOUCHSCREEN == sourceId)
{
int32_t id = AMotionEvent_getAction(event);
switch(id)
{
case AMOTION_EVENT_ACTION_MOVE:
{
size_t    cnt = AMotionEvent_getPointerCount(event);
for( int i = 0 ;i < cnt; ++ i )
{
float x = AMotionEvent_getX(event,i);
float y = AMotionEvent_getY(event,i);
float3 pt;
pt.x = x;
pt.y = y;
pt.z = 0;
g_arVertex.push_back(pt);
}

}
break;
case AMOTION_EVENT_ACTION_DOWN:
{
size_t    cnt = AMotionEvent_getPointerCount(event);
for( int i = 0 ;i < cnt; ++ i )
{
float x = AMotionEvent_getX(event,i);
float y = AMotionEvent_getY(event,i);
}
}
break;
case AMOTION_EVENT_ACTION_UP:
{
size_t    cnt = AMotionEvent_getPointerCount(event);
for( int i = 0 ;i < cnt; ++ i )
{
float x = AMotionEvent_getX(event,i);
float y = AMotionEvent_getY(event,i);
}
}
break;
}
}
else if(AINPUT_SOURCE_TRACKBALL == sourceId)
{
}
}
break;
}
return    0;
}


  该函数主要用于对输入进行判断,以确定是吉键盘、鼠标或遥感等,根据具体输入做相应的操纵,这里就不再做过多的说明

  AMotionEvent_getPointerCount():如果是多点触控,则将各个点保存到vector中。

  2.9 cmd()函数

virtual int    cmd(struct android_app* app, int32_t cmd)
{
switch(cmd)
{
case APP_CMD_SAVE_STATE:
break;
case APP_CMD_INIT_WINDOW:
initDevice();
break;
case APP_CMD_TERM_WINDOW:
shutDownDevice();
break;
case APP_CMD_GAINED_FOCUS:
break;
case APP_CMD_LOST_FOCUS:
break;
}
return    0;
}


  根据传入的命令,对窗口做相应的处理。

  APP_CMD_INIT_WINDOW:表示初始化窗口

  2.10 shutDownDevice()函数

virtual void     shutDownDevice()
{
onDestroy();

if (_display != EGL_NO_DISPLAY)
{
eglMakeCurrent(_display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
if (_context != EGL_NO_CONTEXT)
{
eglDestroyContext(_display, _context);
}
if (_surface != EGL_NO_SURFACE)
{
eglDestroySurface(_display, _surface);
}
eglTerminate(_display);
}
_display = EGL_NO_DISPLAY;
_context = EGL_NO_CONTEXT;
_surface = EGL_NO_SURFACE;
}


  关闭设备,主要是将与设备相关的绑定清除,释放绑定。

编写完上边的代码后,编译程序,将程序导入到模拟器中,最终运行的效果图如下:



好了,该说的基本都说玩了,下边附上源码地址,赶紧去尝试吧:

示例程序下载
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: