Cocos2dx 3.17 Andorid 返回键监听

···在做Cocos2dx 游戏开发时,发现 Android 手机的返回键监听不到了。

我们知道,android 的返回监听 一般通过两个方法,一个是 public void onBackPressed() {}

一个是    public boolean onKeyDown(int keyCode, KeyEvent event){}

而在 Cocos2d android 项目 的 AppActivity 中,这发现这两个方法都没有调用。

所以就在项目中搜索了一下这个两个方法,在  org.cocos2dx.lib中 发现了一个类  Cocos2dxGLSurfaceView,它在实现的时候,重写了onKeyDown() 方法

如下:具体在   org.cocos2dx.lib.Cocos2dxGLSurfaceView 中:

 @Override
    public boolean onKeyDown(final int pKeyCode, final KeyEvent pKeyEvent) {
        switch (pKeyCode) {
            case KeyEvent.KEYCODE_BACK:
                Cocos2dxVideoHelper.mVideoHandler.sendEmptyMessage(Cocos2dxVideoHelper.KeyEventBack);
            case KeyEvent.KEYCODE_MENU:
            case KeyEvent.KEYCODE_DPAD_LEFT:
            case KeyEvent.KEYCODE_DPAD_RIGHT:
            case KeyEvent.KEYCODE_DPAD_UP:
            case KeyEvent.KEYCODE_DPAD_DOWN:
            case KeyEvent.KEYCODE_ENTER:
            case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
            case KeyEvent.KEYCODE_DPAD_CENTER:
                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 true,这样就没法继续向下传递,所以方法没有执行

解决:

对 KeyEvent.KEYCODE_BACK 返回false.

即:

 @Override
    public boolean onKeyDown(final int pKeyCode, final KeyEvent pKeyEvent) {
        switch (pKeyCode) {
            case KeyEvent.KEYCODE_BACK:
                Cocos2dxVideoHelper.mVideoHandler.sendEmptyMessage(Cocos2dxVideoHelper.KeyEventBack);
                return false;
            case KeyEvent.KEYCODE_MENU:
            case KeyEvent.KEYCODE_DPAD_LEFT:
            case KeyEvent.KEYCODE_DPAD_RIGHT:
            case KeyEvent.KEYCODE_DPAD_UP:
            case KeyEvent.KEYCODE_DPAD_DOWN:
            case KeyEvent.KEYCODE_ENTER:
            case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
            case KeyEvent.KEYCODE_DPAD_CENTER:
                this.queueEvent(new Runnable() {
                    @Override
                    public void run() {
                        Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleKeyDown(pKeyCode);
                    }
                });
                return true;
            default:
                return super.onKeyDown(pKeyCode, pKeyEvent);
        }
    }

然后在 AppActivity中实现 onKeyDown() 方法就行了:

   @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Log.d("tag","onKeyDown");
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

打印日志就可以发现,方法得到了执行:

解决!!

 

 

 

 

 

 

 

你可能感兴趣的:(cocos2d-x)