---
title: "控制android手机的back键方法"
author: "wylsx"
date: "2009-11-06T16:17:44Z"
tags: []
slug: "android-back"
draft: false
lastmod: "2009-11-06T16:31:00Z"
id: 511489
url: "https://wylsx.iteye.com/blog/511489"
---

android 的 back键 返回上一级Activity，当然最终会返回到我们的程序的上一级=>主界面，对于很多程序来说不太友好，那么就让我们的程序友好一下吧O(∩_∩)O！

在我们程序的主Activity中 重写一下 onKeyDown事件：

```java

	@Override
	public boolean onKeyDown(int keyCode,KeyEvent event) {
		// 是否触发按键为back键
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			// 弹出 退出确认框
			this.setConfrimDialogListener(new DialogInterface.OnClickListener() {
				// 确定 按钮单击事件
				@Override
				public void onClick(DialogInterface dialog, int which) {
					removeDialog(BaseView.DIALOG_YES_NO_MESSAGE);
					// back键默认执行方法
					// BaseView.this.finish();
					// 结束当前的进程（我们的程序）===>真正意义上的退出
					android.os.Process.killProcess(android.os.Process.myPid());
				}
			});
			this.setConfrimDialogText(R.string.alert_dialog_exit_confirm);
			this.showDialog(BaseView.DIALOG_YES_NO_MESSAGE);
			/*
			 * 下面这句话很重要，return true
			 * 相当于j2se里事件对象的consume()方法，意思是系统不会继续执行该事件，因为已经被消费掉了，O(∩_∩)O~
			 * 可以看该事件的源码说明:* @return boolean Return true if this event was consumed.
			 */
			return true;
		} else// 如果不是back键正常响应
			return super.onKeyDown(int keyCode,event);
	}

```