android 连按两次Back键退出应用

来源:互联网 发布:扬州 住宿 推荐 知乎 编辑:程序博客网 时间:2024/05/21 10:33

来源:
https://stackoverflow.com/questions/20591959/android-quit-application-when-press-back-button
https://stackoverflow.com/questions/8430805/clicking-the-back-button-twice-to-exit-an-activity


代码1

private Boolean exit = false;@Override    public void onBackPressed() {        if (exit) {            finish(); // finish activity        } else {            Toast.makeText(this, "Press Back again to Exit.",                    Toast.LENGTH_SHORT).show();            exit = true;            new Handler().postDelayed(new Runnable() {                @Override                public void run() {                    exit = false;                }            }, 3 * 1000);        }    }

代码2

boolean doubleBackToExitPressedOnce = false;@Overridepublic void onBackPressed() {    if (doubleBackToExitPressedOnce) {        super.onBackPressed();        return;    }    this.doubleBackToExitPressedOnce = true;    Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();    new Handler().postDelayed(new Runnable() {        @Override        public void run() {            doubleBackToExitPressedOnce=false;                               }    }, 2000);} 

end

原创粉丝点击