Toast "Press back again to close" 经常按回键时出错

Toast "Press back again to close" gives error when pressing back too often

我的目标:

当访问者返回到我的应用程序的第一页时,会出现提示消息,让访问者知道他可以在 3 秒内再次按下后退按钮以关闭 Android 应用程序。

具体问题:

当您返回第一页并出现 toast 时,仅按一次后退时代码工作正常,但当出现 toast 并多次按后退时,会出现以下错误消息:“(appname) 已停止".

有谁知道导致此错误消息的原因以及我该如何解决?

MainActivity.java 文件:

// Open previous opened link from history on webview when back button pressed

private Boolean exit = false;
@Override
// Detect when the back button is pressed
public void onBackPressed() {
    if(webView.canGoBack()) {
        webView.goBack();
    }
    else {
        if (exit)
            this.finish();
        else {
            Toast.makeText(this, "Press again to exit.",
                Toast.LENGTH_SHORT).show();
                exit = true;
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        exit = false;
                    }
                }, 3 * 1000);
        }    

    }
}

看起来当您快速单击后退按钮时,它会多次调用 this.finish(),导致崩溃。

你可以做两件事来防止这种情况发生。第一种是在调用 this.finish().

后将 exit 标志设置回 false

此外,为了防止多次快速点击尝试关闭应用程序而出现竞争条件,您可以设置一个时间戳,每三秒只允许安排一个关闭事件 window :

    private Boolean exit = false;
    private long timeStamp = 0;
    private Handler handler = new Handler();
    @Override
    // Detect when the back button is pressed
    public void onBackPressed() {
        if(webView.canGoBack()) {
            webView.goBack();
        }
        else {
            if (exit) {
                exit = false; //added
                this.finish();
            }
            else {

                //added:
                if (timeStamp == 0 || (System.currentTimeMillis() - timeStamp) > 3000) {
                    Toast.makeText(this, "Press again to exit.",
                        Toast.LENGTH_SHORT).show();
                    exit = true;

                    timeStamp = System.currentTimeMillis(); //added

                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            exit = false;
                        }
                    }, 3 * 1000);
                }
            }

        }
    }