在开发过程中使用Android返回键


在开发Android应用时,常常通过按返回键(即keyCode == KeyEvent.KEYCODE_BACK)就能关闭程序,其实大多情况下并没有关闭改应用 

我们可以这样做,当用户点击自定义的退出按钮或返回键时(需要捕获动作),我们在onDestroy()里强制退出应用,或直接杀死进程,具体操作代码如下: 

 
  1. public boolean onKeyDown(int keyCode, KeyEvent event) {     
  2.     
  3.        // 按下键盘上返回按钮     
  4.        if (keyCode == KeyEvent.KEYCODE_BACK) {     
  5.     
  6.            new AlertDialog.Builder(this)     
  7.                    .setMessage("确定退出系统吗?")     
  8.                    .setNegativeButton("取消",     
  9.                            new DialogInterface.OnClickListener() {     
  10.                                public void onClick(DialogInterface dialog,     
  11.                                        int which) {     
  12.                                }     
  13.                            })     
  14.                    .setPositiveButton("确定",     
  15.                            new DialogInterface.OnClickListener() {     
  16.                                public void onClick(DialogInterface dialog,     
  17.                                        int whichButton) {     
  18.                                    finish();     
  19.                                }     
  20.                            }).show();     
  21.     
  22.            return true;     
  23.        } else {     
  24.            return super.onKeyDown(keyCode, event);     
  25.        }     
  26.    }     
  27.     
  28.    @Override     
  29.    protected void onDestroy() {     
  30.        super.onDestroy();     
  31.        // 或者下面这种方式     
  32.        //System.exit(0);     
  33.        //建议用这种     
  34.        android.os.Process.killProcess(android.os.Process.myPid());     
  35.    }    

相关内容