点击返回键关闭应用程序的步骤

来源:互联网 发布:康德 二律背反 知乎 编辑:程序博客网 时间:2024/06/06 01:48

1. 创建一个专门用于app关闭的类

** * 专门用于应用程序关闭的类。 * <p/> * 主要功能: * 1. 创建退出AlertDialog * 2. 释放所有必要资源  *  * @author Lear * */public final class APPCloser {public static Dialog buildLeavingDialog(Context context) {AlertDialog.Builder builder = new AlertDialog.Builder(context);builder.setMessage(R.string.dialog_msg).setPositiveButton(R.string.dialog_confirm,new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int which) {releaseResource();killProcess();}}).setNegativeButton(R.string.dialog_cancel, null);return builder.create();}private static void releaseResource() {// TODO }private static void killProcess() {Process.killProcess(Process.myPid());}}

2. 在MainActivity(也就是主要页面)中,监听返回键事件。

@Overridepublic boolean onKeyDown(int keyCode, KeyEvent event) {if (keyCode == KeyEvent.KEYCODE_BACK) {showDialog(DIALOG_LEAVING_ID);return true;}return super.onKeyDown(keyCode, event);}// --------------------Dialogprivate static final int DIALOG_LEAVING_ID = 0;@Overrideprotected Dialog onCreateDialog(int id, Bundle args) {switch (id) {case DIALOG_LEAVING_ID:return APPCloser.buildLeavingDialog(this);}return null;}

3. 如果有ChildActivity,而且也想让他们,按返回键退出app,可以这样做,即不处理返回键事件,让它继续向上传播。

@Overridepublic boolean onKeyDown(int keyCode, KeyEvent event) {return keyCode == KeyEvent.KEYCODE_BACK ? false : super.onKeyDown(keyCode, event);}



原创粉丝点击