按下后退按钮时忽略某个网页

时间:2015-05-14 09:11:16

标签: android android-webview back-button

最近我为我的Android webview应用添加了一个本地错误页面。因此,当某个网页无法正确加载时,它会显示本地的html文件。

webView.setWebViewClient(new WebViewClient() {      

        //On error, open local file
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            webView.loadUrl("file:///android_asset/www/myerrorpage.html");

        }

});

按下后退按钮时的代码:

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 close.",
                    Toast.LENGTH_SHORT).show();
                exit = true;

                timeStamp = System.currentTimeMillis(); //added

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

    }
}

具体问题:

当我按下后退按钮但我的上一页是“file:///android_asset/www/myerrorpage.html”时,它应该忽略该错误并立即返回到正确加载的最后一个网页。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

@Override
    public void onBackPressed() {
        if (wvContactUs.canGoBack()) {
            wvContactUs.goBack();
        } else {
            super.onBackPressed();
        }
    }



webView.setWebViewClient(new WebViewClient() {      

        //On error, open local file
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            webView.loadUrl("file:///android_asset/www/myerrorpage.html");
                onBackPressed();
        }

});