cocos2dx + android点击返回键两下退出游戏实现

前端之家收集整理的这篇文章主要介绍了cocos2dx + android点击返回键两下退出游戏实现前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1,修改org/cocos2dx/lib/Cocos2dxGLSurfaceView.java下面

@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);
    }
}
为:
@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);
    }
}
按键KeyEvent.KEYCODE_BACK被监听了,只要在这里不作处理即可(return false)

2,添加代码

//
private long exitTime = 0;

@Override
public boolean onKeyDown(int keyCode,KeyEvent event){
	   Log.e("<<<onKeyDown","<<<onKeyDown");
	   if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
		   if(System.currentTimeMillis() - exitTime > 2000){
			   Toast.makeText(getApplicationContext(),"再按一次退出程序",Toast.LENGTH_SHORT).show();
			   exitTime = System.currentTimeMillis();
		   }else{
			   finish();
			   System.exit(0);
		   }
		   return true;
	   }
	   return super.onKeyDown(keyCode,event);
}

猜你在找的Cocos2d-x相关文章