Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android WebView 常見問題大集合與解法

編輯:關於 Android 程式設計

WebView 好用但坑不少,以下把實作中反覆遇到的十五個問題與對應解法整理成清單。

1. 背景設為透明卻沒效果

WebView 預設背景是白色,放在深色頁面上特別突兀。在 2.X 時代,一般寫法是:

wvContent.setBackgroundColor(0);

但換到 4.0 上就失效了,背景照樣是白的。原因是 4.0 起預設開啟硬體加速,解法是針對這個 WebView 關掉硬體加速:

wvContent.setLayerType(View.LAYER_TYPE_SOFTWARE, null);

不過 setLayerType 是 API 11 才有的方法,minSdk 較低時編譯會過不去。這種情況改在布局檔中宣告即可:

android:layerType="software"

經實測,4.0 與 2.2 上都能正常運作,透明背景設定成功。

2. 頁面播放音訊,離開 Activity 後聲音還在響

需要在 onDestroy() 中呼叫 webView.destroy()。但直接呼叫常常會看到這個錯誤:

E/webview(7502): java.lang.Throwable: Error: WebView.destroy() called while still attached!
    at android.webkit.WebViewClassic.destroy(WebViewClassic.java:4142)
    at android.webkit.WebView.destroy(WebView.java:707)
    at com.didi.taxi.ui.webview.OperatingWebViewActivity.onDestroy(OperatingWebViewActivity.java:236)
    ...

意思是 destroy 時 WebView 仍掛在 View 樹上。因為自訂 WebView 建構時傳入了 Activity 的 context,所以必須先從父容器摘掉再銷毀:

rootLayout.removeView(webView);
webView.destroy();

3. 保留縮放功能但隱藏縮放控制器

mWebView.getSettings().setSupportZoom(true);
mWebView.getSettings().setBuiltInZoomControls(true);
if (DeviceUtils.hasHoneycomb()) {
    mWebView.getSettings().setDisplayZoomControls(false);
}

其中 setDisplayZoomControls 是 API 11 才新增的,因此要做版本判斷。

4. 自訂錯誤提示頁

覆寫 WebViewClient 的 onReceivedError(),用一個自訂 View 蓋在 WebView 上:

/** 顯示自訂錯誤頁:用一個 View 覆蓋 WebView */
protected void showErrorPage() {
    LinearLayout webParentView = (LinearLayout) mWebView.getParent();
    initErrorPage();
    while (webParentView.getChildCount() > 1) {
        webParentView.removeViewAt(0);
    }
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
            LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    webParentView.addView(mErrorView, 0, lp);
    mIsErrorPage = true;
}

protected void hideErrorPage() {
    LinearLayout webParentView = (LinearLayout) mWebView.getParent();
    mIsErrorPage = false;
    while (webParentView.getChildCount() > 1) {
        webParentView.removeViewAt(0);
    }
}

protected void initErrorPage() {
    if (mErrorView == null) {
        mErrorView = View.inflate(this, R.layout.online_error, null);
        Button button = (Button) mErrorView.findViewById(R.id.online_error_btn_retry);
        button.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                mWebView.reload();
            }
        });
        mErrorView.setOnClickListener(null);
    }
}

@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
    mErrorView.setVisibility(View.VISIBLE);
    super.onReceivedError(view, errorCode, description, failingUrl);
}

5. 清除 cookies

CookieSyncManager.createInstance(this);
CookieSyncManager.getInstance().startSync();
CookieManager.getInstance().removeSessionCookie();

但 CookieManager 已被標記為過時,官方文件也說明 WebView 現在會自行視需要同步 cookie,因此這段程式在新版本上多半不必再寫。

6. 清除快取與歷史紀錄

webView.clearCache(true);
webView.clearHistory();
m_webview.loadDataWithBaseURL(null, result, "text/html", "utf-8", null);

7. 判斷是否已捲到頁面底部

幾個方法的意義要先分清楚:getScrollY() 回傳目前可見區域頂端距頁面頂端的距離,也就是已捲動的距離;getHeight()/getBottom() 回傳的是 WebView 這個容器本身的高度;getContentHeight() 回傳 HTML 內容高度,但由於 WebView 有縮放,實際頁面高度還要乘上縮放比例。因此準確的判斷是:

if (webView.getContentHeight() * webView.getScale()
        == (webView.getHeight() + webView.getScrollY())) {
    // 已經在底部
}

8. URL 攔截的限制

WebView 攔不到頁面內的 fragment 跳轉。但若用 url 跳轉,又會觸發整頁刷新,H5 體驗就打了折扣。實務上只能透過注入 JS 來解決。

9. 處理非超連結請求(如 Ajax)

有些請求需要加上自訂 header,但 Ajax 這類非超連結請求沒辦法在 shouldOverrideUrlLoading 中攔下來再用 loadUrl(url, headers) 補上。目前採用的應急做法是:先在 url 中打上特殊標記,於 shouldInterceptRequest 攔到時把要加的參數以 query 形式拼上去。這個方法能攔下頁面中的所有資源請求,包含 JS、圖片與 Ajax。

@SuppressLint("NewApi")
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
    // 非超連結(如 Ajax)請求無法直接加 header,改拼到 url 後面,這裡以 imei 為例
    String ajaxUrl = url;
    // 標記:req=ajax
    if (url.contains("req=ajax")) {
        ajaxUrl += "&imei=" + imei;
    }
    return super.shouldInterceptRequest(view, ajaxUrl);
}

10. 讓圖片先顯示出來

@Override
public void onLoadResource(WebView view, String url) {
    mEventListener.onWebViewEvent(CustomWebView.this,
            OnWebViewEventListener.EVENT_ON_LOAD_RESOURCE, url);
    if (url.indexOf(".jpg") > 0) {
        hideProgress(); // 開始載入圖片時就先把頁面顯示出來
        mEventListener.onWebViewEvent(CustomWebView.this,
                OnWebViewEventListener.EVENT_ON_HIDE_PROGRESS, view.getUrl());
    }
    super.onLoadResource(view, url);
}

11. 屏蔽長按選單

長按 WebView 會跳出系統的複製選單,若不需要可以用空實作吃掉事件:

mWebView.setOnLongClickListener(new OnLongClickListener() {
    @Override
    public boolean onLongClick(View v) {
        return true;
    }
});

12. 在 WebView 中支援 Flash

String temp = "<embed src=\"...\" height=\"90%\" scale=\"noscale\" "
        + "type=\"application/x-shockwave-flash\">";
web.loadDataWithBaseURL("null", temp, "text/html", "utf-8", "");

13. Android 4.4 上 onPageFinished 會多呼叫一次

盡量不要在 onPageFinished() 裡寫業務邏輯,否則會重複觸發,甚至造成狀態錯亂。

14. 抓取網頁 title 用來設定自家標題欄

給 WebView 掛上 WebChromeClient,在 onReceivedTitle() 中取用:

WebChromeClient webChromeClient = new WebChromeClient() {
    @Override
    public void onReceivedTitle(WebView view, String title) {
        super.onReceivedTitle(view, title);
        txtTitle.setText(title);
    }
};

但在部分機型(例如小米 3)上,透過 goBack() 回退時不會觸發 onReceivedTitle,標題會停留在上一個子頁面的文字。處理方式分兩種:

其一,若確定只有一層二級頁面,只要判斷是否為起始頁,能 goBack 時把標題設回預設值即可。

其二,若存在多層頁面或日後可能擴充,就得自己維護一份 url 堆疊與 url 到 title 的對應:用一個 List 記錄已載入的 url,一個 Map 存 url 與 title 的對應關係。正常載入時寫入,回退時移掉目前 url、取出目標 url 並套用對應標題。另外要注意,載入失敗(例如無網路)時,onReceivedTitle 拿到的會是「找不到該網頁」這類系統文案,因此觸發 onReceivedError 時不要採用這個 title。

15. addJavaScriptInterface 帶來的安全風險

這個 API 可能被惡意 JS 利用進行注入攻擊,在已取得 root 權限的裝置上尤其危險,攻擊者有機會藉此安裝或卸載應用。可行的替代方案是改用 onJsPrompt() 建構 JS 與原生之間的橋梁,並搭配非同步回呼,能相應地補強注入面的風險。相關實作可參考開源專案 https://github.com/pedant/safe-java-js-webview-bridge 。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved