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(也就是主要页面)中,监听返回键事件。
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
showDialog(DIALOG_LEAVING_ID);
return true;
}
return super.onKeyDown(keyCode, event);
}
// --------------------Dialog
private static final int DIALOG_LEAVING_ID = 0;
@Override
protected Dialog onCreateDialog(int id, Bundle args) {
switch (id) {
case DIALOG_LEAVING_ID:
return APPCloser.buildLeavingDialog(this);
}
return null;
}
3. 如果有ChildActivity,而且也想让他们,按返回键退出app,可以这样做,即不处理返回键事件,让它继续向上传播。
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
return keyCode == KeyEvent.KEYCODE_BACK ? false : super.onKeyDown(
keyCode, event);
}