原文地址:http://50vip.com/390.html
一般的游戏或者软件,都会在android版本上做退出程序的功能,一般的实现方式有两种:
1.点击返回按键,弹出确认是否退出;
这两种方式实现都需要android上监听用户按下了android手机上的返回键,监听到了之后执行相应的操作。
public boolean onKeyDown(final int pKeyCode,final KeyEvent pKeyEvent)
实现对用户按键的监听,但是将代码加入到cocos2d-x生成的Java代码中的AppActivity中,发现根本不起作用,没法监听到用户的按键操作,找官方api文档,发现:
public booleanonKeyDown(int keyCode,KeyEventevent)
Since:API Level 1
Called when a key was pressed down and not handled by any of the views inside of the activity.So,for example,key presses while the cursor is inside a TextView will not trigger the event (unless it is a navigation to another object) because TextView handles its own key presses.
If the focused view didn't want this event,this method is called.
这段文字我需要强调的是红色标记部分,翻译的意思是:当用户按下一个按键的时候调用,但是前提是这个事件没有被其他的任何views监听并处理。
因此不难得知,在cocos2d-x游戏中,在实现的onKeyDown方法监听不到返回键,是因为这个返回键事件已经被其他的onKeyDown处理掉了,具体是谁呢?看cocos2d-x的android版本代码(framework/scocos2d-x/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dx/GLSurfaceView.java)。其中实现了onKeyDown方法:
@Override public boolean onKeyDown(final int pKeyCode,final KeyEvent pKeyEvent) { switch (pKeyCode) { case KeyEvent.KEYCODE_BACK: case KeyEvent.KEYCODE_MENU: this.queueEvent(new Runnable() { @Override public void run() { Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleKeyDown(pKeyCode); } }); return true; default: return super.onKeyDown(pKeyCode,pKeyEvent); } }
这个里面,按键KeyEvent.KEYCODE_BACK被监听了,只要在这里不作处理即可(return false),改成如下代码:
@Override public boolean onKeyDown(final int pKeyCode,final KeyEvent pKeyEvent) { switch (pKeyCode) { case KeyEvent.KEYCODE_BACK: return false; case KeyEvent.KEYCODE_MENU: this.queueEvent(new Runnable() { @Override public void run() { Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleKeyDown(pKeyCode); } }); return true; default: return super.onKeyDown(pKeyCode,pKeyEvent); } }这样在你自己的cocos2d-x游戏Activity中就可以监听返回键了,在AppActivity中重写onKeyDown方法,如下:
private long mkeyTime = 0; public boolean onKeyDown(int keyCode,KeyEvent event) { //二次返回退出 if (keyCode == KeyEvent.KEYCODE_BACK) { if ((System.currentTimeMillis() - mkeyTime) > 2000) { mkeyTime = System.currentTimeMillis(); Toast.makeText(this,"再按一次退出游戏",Toast.LENGTH_LONG).show(); } else { finish(); System.exit(0); } return false; } return super.onKeyDown(keyCode,event); }然后运行游戏, 点击返回键试试,有没有Toast?