1. 程式人生 > >Android WebView載入網頁失敗處理

Android WebView載入網頁失敗處理

  WebView在載入網頁的時候,如果載入失敗,顯示系統預設的錯誤頁面很醜,而且很噁心,會暴露url。一般操作處理:自定義一個錯誤頁面。這個頁面可以是一個本地網頁,也可以是Android頁面。
  技術點:重寫WebViewClient裡面的onReceivedError();
  onReceivedError呼叫情況:onReceivedError只有在遇到不可用的(unrecoverable)錯誤時,才會被呼叫)。 
  比如,當WebView載入連結www.baidu.com時,”不可用”的情況有可以包括有:
  1、沒有網路連線
  2、連線超時
  3、找不到頁面www.baidu.com
  而下面的情況則不會被報告:
  1、網頁內引用其他資源載入錯誤,比如圖片、css不可用
  2、js執行錯誤

  具體處理程式碼:

`

class MyClient extends WebViewClient {
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override

        //Log.e(TAG, "shouldOverrideUrlLoading: (new)-----" + String.valueOf(request.getUrl()));
        return false;
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        //Log.e(TAG, "onPageStarted: ----url:" + url);
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        mProgressBar.setVisibility(View.GONE);
        if (mIsLoadSuccess) {
            mErrorView.setVisibility(View.GONE);
            mWebView.setVisibility(View.VISIBLE);
            //根據Url處理自己的業務
            handleWebRequest(url);
        } else {
            mErrorView.setVisibility(View.VISIBLE);
            mWebView.setVisibility(View.GONE);
        }
    }

    /**
     * 這裡進行無網路或錯誤處理,具體可以根據errorCode的值進行判斷,做跟詳細的處理。
     *
     * @param view
     */
    // 舊版本,會在新版本中也可能被呼叫,所以加上一個判斷,防止重複顯示
    @Override
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        super.onReceivedError(view, errorCode, description, failingUrl);
        //Log.e(TAG, "onReceivedError: ----url:" + error.getDescription());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return;
        }
        // 在這裡顯示自定義錯誤頁
        mErrorView.setVisibility(View.VISIBLE);
        mWebView.setVisibility(View.GONE);
        mProgressBar.setVisibility(View.GONE);
        mIsLoadSuccess = false;
    }

    // 新版本,只會在Android6及以上呼叫
    @TargetApi(Build.VERSION_CODES.M)
    @Override
    public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
        super.onReceivedError(view, request, error);
        if (request.isForMainFrame()) { // 或者: if(request.getUrl().toString() .equals(getUrl()))
            // 在這裡顯示自定義錯誤頁
            mErrorView.setVisibility(View.VISIBLE);
            mWebView.setVisibility(View.GONE);
            mIsLoadSuccess = false;
        }
    }
}`