Android - 优化WebView页面

jopen 9年前

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/

来自: http://blog.csdn.net//caroline_wendy/article/details/48469005