Android - 最佳化WebView頁面

來源:互聯網
上載者:User

標籤:mystra   android   最佳化webview   

WebView包含基礎的HTML顯示功能, 使用時, 需要進行多方面的最佳化.
(1) 常用設定
(2) 網頁用戶端
(3) 瀏覽器用戶端
(4) 捲軸
(5) 擷取網頁內容

Code:

package me.chunyu.Pedometer.base;import android.annotation.SuppressLint;import android.content.Context;import android.util.AttributeSet;import android.util.Log;import android.view.View;import android.webkit.JavascriptInterface;import android.webkit.JsResult;import android.webkit.WebChromeClient;import android.webkit.WebSettings;import android.webkit.WebView;import android.webkit.WebViewClient;/** * 用於控制WebView的View * 由於使用WebView的類型太多,如Activity,Fragment,DialogFragment等 * 因此將WebView的功能獨立出來作為一個View * * @author MasaWong * @author wangchenlong */@SuppressWarnings({"unused", "WeakerAccess"})public class PedoWebView extends WebView {    private static final String TAG = "DEBUG-WCL: " + PedoWebView.class.getSimpleName();    @SuppressWarnings("SpellCheckingInspection")    private static final String JS_PROCESS_TAG = "HTMLOUT"; // 用於獲得HTML的內容    // 用於獲得HTML的內容, 固定格式{@link MyJavaScriptInterface}    private static final String HTML_CONTENT = "javascript:window." + JS_PROCESS_TAG            + ".processHTML(‘<head>‘+document.getElementsByTagName(‘html‘)[0].innerHTML+‘</head>‘);";    private ReceivedTitleListener mReceivedTitleListener;    private PageFinishedListener mPageFinishedListener;    private ReceivedErrorListener mReceivedErrorListener;    private UrlLoadingListener mUrlLoadingListener;    private JsAlertListener mJsAlertListener;    public PedoWebView(Context context) {        super(context);        if (!isInEditMode())            init();    }    public PedoWebView(Context context, AttributeSet attrs) {        super(context, attrs, 0);        if (!isInEditMode())            init();    }    public PedoWebView(Context context, AttributeSet attrs, int defStyle) {        super(context, attrs, defStyle);        // 資源顯示        if (!isInEditMode())            init();    }    /**     * 建構函式,配置WebView     */    @SuppressLint("AddJavascriptInterface")    public void init() {        // clearView() is deprecated, but onBackPressed returns to about:blank        //noinspection deprecation        clearView();        setWebViewClient();        setWebChromeClient();        setWebViewSettings();        setHorizontalScrollBarEnabled(false);        // 捲軸不佔位        setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);        addJavascriptInterface(new MyJavaScriptInterface(), JS_PROCESS_TAG);    }    /**     * 配置WebView參數     */    @SuppressLint("SetJavaScriptEnabled")    protected void setWebViewSettings() {        WebSettings settings = getSettings();        // User settings        settings.setJavaScriptEnabled(true); // 允許彈窗        settings.setLoadsImagesAutomatically(true);        settings.setUseWideViewPort(true);        settings.setLoadWithOverviewMode(false);        // Technical settings        settings.setSupportMultipleWindows(true); // 支援多視窗        settings.setAppCacheEnabled(true);        settings.setDatabaseEnabled(true);        settings.setDomStorageEnabled(true);        // 優先使用緩衝        settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);    }    /**     * 配置WebViewClient來處理網頁載入的各種狀態     */    protected void setWebViewClient() {        WebViewClient webClient = new WebViewClient() {            // 重新導向會載入多次            @Override            public void onPageFinished(WebView view, String url) {                getSettings().setBlockNetworkImage(false);                if (mPageFinishedListener != null) {                    mPageFinishedListener.overridePageFinished(view, url);                }                loadUrl(HTML_CONTENT); // 載入JS內容            }            @Override            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {                if (mReceivedErrorListener != null) {                    mReceivedErrorListener.overrideReceivedError(view, errorCode,                            description, failingUrl);                }            }            @Override            public boolean shouldOverrideUrlLoading(WebView view, String url) {                return mUrlLoadingListener != null &&                        mUrlLoadingListener.overrideUrlLoading(view, url);            }        };        setWebViewClient(webClient);    }    /**     * 獲得JS的內容     */    class MyJavaScriptInterface {        @JavascriptInterface        @SuppressWarnings("unused")        public void processHTML(String html) {            Log.d(TAG, "諮詢醫生的H5頁面: " + html);        }    }    /**     * 配置WebChromeClient來處理JsAlert,用於從網頁取得一些複雜的資料     */    protected void setWebChromeClient() {        WebChromeClient webChromeClient = new WebChromeClient() {            @Override            public void onReceivedTitle(WebView view, String title) {                if (mReceivedTitleListener != null) {                    mReceivedTitleListener.onReceivedTitle(view, title);                }            }            @Override            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {                return mJsAlertListener != null &&                        mJsAlertListener.overrideJsAlert(view, url, message, result);            }        };        setWebChromeClient(webChromeClient);    }    /**     * 載入Url     *     * @param url 需要載入的url     */    @Override    public void loadUrl(String url) {        // 把圖片載入放在最後來載入渲染        getSettings().setBlockNetworkImage(true);        super.loadUrl(url);    }    public void setReceivedTitleListener(ReceivedTitleListener receivedTitleListener) {        mReceivedTitleListener = receivedTitleListener;    }    public void setPageFinishedListener(PageFinishedListener pageFinishedListener) {        mPageFinishedListener = pageFinishedListener;    }    public void setReceivedErrorListener(ReceivedErrorListener receivedErrorListener) {        mReceivedErrorListener = receivedErrorListener;    }    public void setUrlLoadingListener(UrlLoadingListener urlLoadingListener) {        mUrlLoadingListener = urlLoadingListener;    }    public void setJsAlertListener(JsAlertListener jsAlertListener) {        mJsAlertListener = jsAlertListener;    }    public interface ReceivedTitleListener {        void onReceivedTitle(WebView view, String title);    }    public interface PageFinishedListener {        void overridePageFinished(WebView view, String url);    }    public interface ReceivedErrorListener {        void overrideReceivedError(WebView view, int errorCode, String description,                                   String failingUrl);    }    public interface UrlLoadingListener {        boolean overrideUrlLoading(WebView view, String url);    }    public interface JsAlertListener {        boolean overrideJsAlert(WebView view, String url, String message, JsResult result);    }}

參考: http://www.pedant.cn/2014/09/10/webview-optimize-points/

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

Android - 最佳化WebView頁面

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.