重写onKeyDown方法
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {// 按返回键提示 if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) { Dialog dialog = new AlertDialog.Builder(MainActivity.this) .setTitle("提示") .setMessage("是否退出程序") .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { finish(); } }) .setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { dialog.cancel(); } }).create();// 创建按钮 dialog.show(); } return super.onKeyDown(keyCode, event); }