首页 > 代码库 > 退出应用总结

退出应用总结

1. 按两下返回键退出

代码如下:

private long exitTime = 0; 
   @Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    ExitApp();
    return false;
}
public void ExitApp() {
    if ((System.currentTimeMillis() - exitTime) > 2000) {
	Toast.makeText(MainActivity.this, "再按一次退出程序", 0).show();
	exitTime = System.currentTimeMillis();
    } else {
	finish(); //关闭当前Activity
    }
}

注:这种方式退出程序是绑定的为设置的按键。Called when a key was pressed down and not handled by any of the views inside of the activity.即按返回和菜单按键都会达到相同的效果。

2. 按返回键弹出对话框

@Override
public void onBackPressed() {
    AlertDialog.Builder builder = new Builder(this);
    builder.setTitle("离开提醒");
    builder.setMessage("真的不需要我了么?");
    builder.setPositiveButton("确定", new OnClickListener() {
	@Override
	public void onClick(DialogInterface dialog, int which) {
	    finish();
	//安全退出进程
	//杀死 的操作  (专注于自杀的操作)
	android.os.Process.killProcess(android.os.Process.myPid());
    }
});
builder.setNegativeButton("取消", null);
builder.show();
}

3. 退出时资源释放问题

可以只是退出Activity,调用finish()方法,此时改程序的进程将变为空进程驻留在内存中;

也可以采用环保的方式,退出时将自己程序的进程杀死,android.os.Process.killProcess(android.os.Process.myPid());