1,包含头文件
import android.util.Log;
import android.view.KeyEvent;
2,复制粘贴下面代码即可:
// 重写方法
public boolean dispatchKeyEvent(KeyEvent event) {
// TODO Auto-generated method stub
if (event.getAction() == KeyEvent.ACTION_DOWN
&& event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
Log.i(TAG, "onKeyDown() ==================================");
ExitDialog(AppActivity.this).show();
//do something what you want
return true;//返回true,把事件消费掉,不会继续调用onBackPressed
}
return super.dispatchKeyEvent(event);
}
private Dialog ExitDialog(Context context) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setIcon(R.drawable.icon); //选择对应的包 icon package="****"
builder.setTitle("应用名称");
builder.setMessage("是否确定退出!!!");
builder.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//进行一些操作,任意
Log.i(TAG, "setNegativeButton() 确定 ====");
System.exit(-1); // 退出应用
}
});
builder.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//进行一些操作,任意
Log.i(TAG, "setNegativeButton() 取消 =========");
}
});
return builder.create();
}
注:Key up dispatch to org.cocos2dx.lib.Cocos2dxGLSurfaceView{bd9ad39 VFE...... .F....I. 0,0-1920,1080}, event = KeyEvent { action=ACTION_UP, keyCode=KEYCODE_BACK, scanCode=158, metaState=0, flags=0x68, repeatCount=0, eventTime=260314397, downTime=260314360, deviceId=15, source=0x101 }