程序都需要退出确认功能,方式有很多种。不多说。
方法一:
- @Override
- public boolean dispatchKeyEvent(KeyEvent event) {
- if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
- if (event.getAction() == KeyEvent.ACTION_DOWN
- && event.getRepeatCount() == 0) {
- this.confirmExit();// 这是自定义的代码
- }
- return true;
- }
- return super.dispatchKeyEvent(event);
- }
- private void confirmExit() {
- // 退出确认
- AlertDialog.Builder ad = new AlertDialog.Builder(PGisMainActivity.this);
- ad.setTitle("退出");
- ad.setIcon(R.drawable.ic_launcher);
- ad.setMessage("是否退出系统?");
- ad.setPositiveButton("是", new DialogInterface.OnClickListener() {
- // 退出按钮
- @Override
- public void onClick(DialogInterface dialog, int i) {
- isRunning = false;
- }
- });
- ad.setNegativeButton("否", new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int i) {
- // 不退出不用执行任何操作
- }
- });
- ad.show();// 显示对话框
- }
- @Override
- public boolean onKeyDown(int keyCode, KeyEvent event) {
- if (keyCode == KeyEvent.KEYCODE_BACK) {
- exitApplication();
- }
- return true;
- }
- private void exitApplication() {
- Builder builder = new Builder(this);
- builder.setIcon(R.drawable.ic_launcher);
- builder.setTitle("退出");
- builder.setMessage("确定退出吗?");
- builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int which) {
- System.exit(0);
- }
- });
- builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface arg0, int arg1) {
- }
- });
- builder.show();
- }