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

来源:互联网 发布:网络文件共享平台 编辑:程序博客网 时间:2024/05/02 01:11

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

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

  

view plain
  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.    }   

原创粉丝点击