(framework/scocos2d-x/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dx/GLSurfaceView.java)。其中實現了onKeyDown方法: java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
@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),改爲以下代碼: android
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
@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方法,以下: ide
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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? this