Android WebView使用詳解

一、簡介

WebView是一個基於webkit引擎、展現web頁面的控件,(注:android的Webview在低版本和高版本採用了不同的webkit版本內核,4.4後直接使用了Chrome。)

二、作用

     2.1、顯示和渲染Web頁面
     2.2、直接使用html文件(網絡上或本地assets中)作佈局
     2.3、可和JavaScript交互調用

三、WebView常用方法介紹

    3.1、loadUrl()

           //方式1. 加載一個網頁:
            webView.loadUrl("http://www.google.com/");
           //方式2:加載apk包中的html頁面
            webView.loadUrl("file:///android_asset/test.html");
           //方式3:加載手機本地的html頁面
            webView.loadUrl("content://com.android.htmlfileprovider/sdcard/test.html");
    3.2、loadData()

           //加載 HTML 頁面的一小段內容
           webView.loadData(String data, String mimeType, String encoding)
           // 參數1:需要截取展示的內容(不能包含特殊字符:#、%、\,?)
           // 參數2:展示內容的類型
           // 參數3:字節碼
    3.3、loadDataWithBaseURL()

          // 顯示文字與圖片內容(支持多個模擬器版本) 
         webview.loadDataWithBaseURL(String baseUrl,String data,String mimeType,String encoding,String historyUrl);
         // 參數1:相關資源的相對根路徑
         // 參數2:需要截取展示的內容(不能包含特殊字符:#、%、\,?)
         // 參數3:展示內容的類型
         // 參數4:字節碼
         // 參數5:也可以指定歷史Url

    3.4、其他設置方法

         setJavaScriptEnabled(true);  //支持js
         setPluginsEnabled(true);  //支持插件 
         setUseWideViewPort(false);  //將圖片調整到適合webview的大小 
         setSupportZoom(true);  //支持縮放 
         setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN); //支持內容重新佈局  
         supportMultipleWindows();  //多窗口 
         setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);  //關閉webview中緩存 
         setAllowFileAccess(true);  //設置可以訪問文件 
         setNeedInitialFocus(true); //當webview調用requestFocus時爲webview設置節點
         webview webSettings.setBuiltInZoomControls(true); //設置支持縮放 
         setJavaScriptCanOpenWindowsAutomatically(true); //支持通過JS打開新窗口 
         setLoadWithOverviewMode(true); // 縮放至屏幕的大小
         setLoadsImagesAutomatically(true);  //支持自動加載圖片

四、WebView常用類介紹

     4.1、WebSettings類

          //聲明WebSettings子類
         WebSettings webSettings = webView.getSettings();

         //如果訪問的頁面中要與Javascript交互,則webview必須設置支持Javascript
         webSettings.setJavaScriptEnabled(true);  
         // 若加載的 html 裏有JS 在執行動畫等操作,會造成資源浪費(CPU、電量)
         // 在 onStop 和 onResume 裏分別把 setJavaScriptEnabled() 給設置成 false 和 true 即可

         //支持插件
         webSettings.setPluginsEnabled(true); 

         //設置自適應屏幕,兩者合用
         webSettings.setUseWideViewPort(true); //將圖片調整到適合webview的大小 
         webSettings.setLoadWithOverviewMode(true); // 縮放至屏幕的大小

         //縮放操作
         webSettings.setSupportZoom(true); //支持縮放,默認爲true。是下面那個的前提。
         webSettings.setBuiltInZoomControls(true); //設置內置的縮放控件。若爲false,則該WebView不可縮放
         webSettings.setDisplayZoomControls(false); //隱藏原生的縮放控件

         //其他細節操作
         webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //關閉webview中緩存 
         webSettings.setAllowFileAccess(true); //設置可以訪問文件 
         webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通過JS打開新窗口 
         webSettings.setLoadsImagesAutomatically(true); //支持自動加載圖片
         webSettings.setDefaultTextEncodingName("utf-8");//設置編碼格式

     4.2、WebViewClient類

    webview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {

            }

            @Override
            public void onPageFinished(WebView view, String url) {

            }

            @Override
            public void onLoadResource(WebView view, String url) {
                super.onLoadResource(view, url);
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
            }
      });
           4.2.1 shouldOverrideUrlLoading() 方法

              打開網頁時不調用系統瀏覽器, 而是在本WebView中顯示;在網頁上的所有加載都經過這個方法,這個函數我們可以做很多操作。

       webView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                  view.loadUrl(url);
               return true;
            }
        });

          4.2.2  onPageStarted() 方法

              開始載入頁面調用的,我們可以設定一個loading的頁面,告訴用戶程序在等待網絡響應

       webView.setWebViewClient(new WebViewClient(){
            @Override
            public void  onPageStarted(WebView view, String url, Bitmap favicon) {
                //設定加載開始的操作
            }
       });

          4.2.3 onPageFinished() 方法
              在頁面加載結束時調用。我們可以關閉loading 條,切換程序動作

       webView.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView view, String url) {
                 //設定加載結束的操作
            }
       });

          4.2.4 onLoadResource() 方法

              在加載頁面資源時會調用,每一個資源(比如圖片)的加載都會調用一次

       webView.setWebViewClient(new WebViewClient(){
           @Override
           public boolean onLoadResource(WebView view, String url) {
                //設定加載資源的操作
           }
       });

         4. 2.5 onReceivedError() 方法

              加載頁面的服務器出現錯誤時(如404)調用

       webView.setWebViewClient(new WebViewClient(){
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl){
                 switch(errorCode){
                    case HttpStatus.SC_NOT_FOUND:
                         view.loadUrl("file:///android_assets/error_handle.html");
                    break;
                 }
            }
        });

          4.2.6 onReceivedSslError() 方法

              處理https請求出錯

            (注:當使用webview控件請求時遇到了諸如404這類的錯誤的時候,這時候我們的app就需要加載一個本地的錯誤提示頁面,即webview如何加載一個本地的頁面)

       webView.setWebViewClient(new WebViewClient() {    
            @Override    
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {    
                 handler.proceed();    //表示等待證書響應
                 // handler.cancel();      //表示掛起連接,爲默認方式
                 // handler.handleMessage(null);    //可做其他處理
            }    
       });

     4.3、WebChromeClient類

      webview.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                return super.onJsAlert(view, url, message, result);
            }

            @Override
            public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
                return super.onJsConfirm(view, url, message, result);
            }

            @Override
            public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
                return super.onJsPrompt(view, url, message, defaultValue, result);
            }
       });
         4.3.1 onReceivedTitle() 方法

               獲取Web頁中的標題

       webview.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onReceivedTitle(WebView view, String title) {
                 titleview.setText(title);
            } 
        });

         4.3.2 onProgressChanged() 方法

                獲得網頁的加載進度並顯示

        webview.setWebChromeClient(new WebChromeClient(){
             @Override
             public void onProgressChanged(WebView view, int newProgress) {
                  if (newProgress < 100) {
                       String progress = newProgress + "%";
                       progress.setText(progress);
                  } else if (newProgress == 100) {
                       String progress = 100+ "%";
                       progress.setText(progress);
	          }
             }
        });

         4.3.3 onJsAlert() 方法

               支持javascript的警告框

       webview.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onJsAlert(WebView view, String url, String message, final JsResult result)  {
                 new AlertDialog.Builder(MainActivity.this)
                   .setTitle("JsAlert")
                   .setMessage(message)
                   .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                         @Override
                         public void onClick(DialogInterface dialog, int which) {
                               result.confirm();
                         }
                 })
                .setCancelable(false)
                .show();
             return true;
            }
        });

         4.3.4 onJsConfirm() 方法

               支持javascript的確認框

       webview.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
                new AlertDialog.Builder(MainActivity.this)
                .setTitle("JsConfirm")
                .setMessage(message)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                      @Override
                      public void onClick(DialogInterface dialog, int which) {
                           result.confirm();
                      }
                })
               .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                      @Override
                      public void onClick(DialogInterface dialog, int which) {
                           result.cancel();
                      }
                 })
                .setCancelable(false)
                .show();
              // 返回布爾值:判斷點擊時確認還是取消
              // true表示點擊了確認;false表示點擊了取消;
             return true;
             }
        });

         4.3.5 onJsPrompt() 方法

               支持javascript輸入框

       webview.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, final JsPromptResult result) {
                 final EditText et = new EditText(MainActivity.this);
                 et.setText(defaultValue);
                 new AlertDialog.Builder(MainActivity.this)
                 .setTitle(message)
                 .setView(et)
                 .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                       @Override
                       public void onClick(DialogInterface dialog, int which) {
                            result.confirm(et.getText().toString());
                       }
                  })
                 .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                       @Override
                       public void onClick(DialogInterface dialog, int which) {
                            result.cancel();
                       }
                  })
                 .setCancelable(false)
                 .show();
              return true;
              }
        });

五、WebView的生命週期方法

    5.1 webView.onResume() ;
         激活WebView爲活躍狀態,能正常執行網頁的響應
    5.2 webView.onPause();
         當頁面被失去焦點被切換到後臺不可見狀態,需要執行onPause
         通過onPause動作通知內核暫停所有的動作,比如DOM的解析、plugin的執行、JavaScript執行。
    5.4 webView.pauseTimers()
         當應用程序(存在webview)被切換到後臺時,這個方法不僅僅針對當前的webview而是全局的全應用程序的webview
         它會暫停所有webview的layout,parsing,javascripttimer。降低CPU功耗。
    5.5 webView.resumeTimers();
         恢復pauseTimers狀態
    5.6 webView.destroy();
         在關閉了Activity時,如果Webview的音樂或視頻,還在播放。就必須銷燬Webview
         但是注意:webview調用destory時,webview仍綁定在Activity上
         這是由於自定義webview構建時傳入了該Activity的context對象
         因此需要先從父容器中移除webview,然後再銷燬webview: rootLayout.removeView(webView)

六、關於前進和後退的方法

    6.1 前進
         //是否可以前進                     
        webview.canGoForward()
        //前進網頁
        webview.goForward()
    6.2 後退
        //是否可以後退
        webview.canGoBack() 
        //後退網頁
        webview.goBack()
    6.3 webview.goBackOrForward()
         以當前的index爲起始點前進或者後退到歷史記錄中指定的steps,如果steps爲負數則爲後退,正數則爲前進
    6.4 Back鍵控制網頁後退
         在不做任何處理前提下,瀏覽網頁時點擊系統的“Back”鍵,整個瀏覽器會調用 finish()而結束自身
         如果想點擊返回後,是網頁回退而不是推出瀏覽器,則需要這麼解決:

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KEYCODE_BACK) && webView.canGoBack()) { 
            webView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

七、緩存數據的操作

    7.1 設置緩存的方法

         7.1.1 設置緩存的優先級:
                  WebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); 
                      //緩存模式如下:
                      //LOAD_CACHE_ONLY: 不使用網絡,只讀取本地緩存數據
                      //LOAD_DEFAULT: (默認)根據cache-control決定是否從網絡上取數據。
                      //LOAD_NO_CACHE: 不使用緩存,只從網絡獲取數據.
                     //LOAD_CACHE_ELSE_NETWORK,只要本地有,無論是否過期,或者no-cache,都使用緩存中的數據。
         7.1.2 結合使用(離線加載)例子:
         if (NetStatusUtil.isConnected(getApplicationContext())) {
            webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);//根據cache-control決定是否從網絡上取數據。
         } else {
            webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);//沒網,則從本地獲取,即離線加載
         }
        webSettings.setDomStorageEnabled(true); // 開啓 DOM storage API 功能
        webSettings.setDatabaseEnabled(true);   //開啓 database storage API 功能
        webSettings.setAppCacheEnabled(true);//開啓 Application Caches 功能
        String cacheDirPath = getFilesDir().getAbsolutePath() + APP_CACAHE_DIRNAME;
        webSettings.setAppCachePath(cacheDirPath); //設置  Application Caches 緩存目錄
     (注:1、每個 Application 只調用一次 WebSettings.setAppCachePath(),WebSettings.setAppCacheMaxSize()
                 2、當加載 html 頁面時,WebView會在/data/data/包名目錄下生成database與cache兩個文件夾請求的 URL記錄保存在 WebViewCache.db,而 URL的內容是保存在 WebViewCache 文件夾下)

    7.2 清除緩存的方法

          7.2.1 webview.clearCache(true);
                    清除網頁訪問留下的緩存,由於內核緩存是全局的因此這個方法不僅僅針對webview而是針對整個應用程序.
          7.2.2 webview.clearHistory()
                    清除當前webview訪問的歷史記錄,只會webview訪問歷史記錄裏的所有記錄除了當前訪問記錄.
          7.2.3 webview.clearFormData();
                   僅僅清除自動完成填充的表單數據,並不會清除WebView存儲到本地的數據

八、避免WebView內存泄露

     8.1 在Activity中創建,使用getApplicationgContext()對象上下文
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        webView = new WebView(getApplicationContext());
        webView.setLayoutParams(params);
        mLayout.addView(webView);

     8.2 在 Activity 銷燬( WebView )的時候,先讓 WebView 加載null內容,然後移除 WebView,再銷燬 WebView,最後置空。

    @Override
    protected void onDestroy() {
        if (webView != null) {
            webView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            webView.clearHistory();

            ((ViewGroup) webView.getParent()).removeView(webView);
            webView.destroy();
            webView = null;
        }
        super.onDestroy();
    }

九、優點

     9.1 開發成本低,可以適配多種平臺的設備

     9.2 迭代更新成本低,可以快速的實現更新的內容全覆蓋

十、案例

步棸1 :添加網絡權限

<uses-permission android:name="android.permission.INTERNET"/>

步棸2:佈局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <!-- 獲取網站的標題-->
    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="獲取網站的標題" />

    <!--開始加載提示-->
    <TextView
        android:id="@+id/text_beginLoading"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" />

    <!--獲取加載進度-->
    <TextView
        android:id="@+id/text_Loading"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" />

    <!--結束加載提示-->
    <TextView
        android:id="@+id/text_endLoading"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" />

    <!--顯示網頁區域-->
    <WebView
        android:id="@+id/webView1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_marginTop="10dp" />

</LinearLayout>

步棸3:MainActivity.class

import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    WebView mWebview;
    WebSettings mWebSettings;
    TextView beginLoading, endLoading, loading, mtitle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mWebview = (WebView) findViewById(R.id.webView1);
        beginLoading = (TextView) findViewById(R.id.text_beginLoading);
        endLoading = (TextView) findViewById(R.id.text_endLoading);
        loading = (TextView) findViewById(R.id.text_Loading);
        mtitle = (TextView) findViewById(R.id.title);
        mWebSettings = mWebview.getSettings();
        mWebview.loadUrl("http://www.baidu.com/");

        //設置WebViewClient類
        mWebview.setWebViewClient(new WebViewClient() {
            //設置不用系統瀏覽器打開,直接顯示在當前Webview
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            //設置加載前的函數
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                beginLoading.setText("開始加載了");

            }

            //設置結束加載函數
            @Override
            public void onPageFinished(WebView view, String url) {
                endLoading.setText("結束加載了");

            }
        });


        //設置WebChromeClient類
        mWebview.setWebChromeClient(new WebChromeClient() {


            //獲取網站標題
            @Override
            public void onReceivedTitle(WebView view, String title) {
                System.out.println("標題在這裏");
                mtitle.setText(title);
            }

            //獲取加載進度
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress < 100) {
                    String progress = newProgress + "%";
                    loading.setText(progress);
                } else if (newProgress == 100) {
                    String progress = newProgress + "%";
                    loading.setText(progress);
                }
            }
        });
    }

    //點擊返回上一頁面而不是退出瀏覽器
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && mWebview.canGoBack()) {
            mWebview.goBack();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    //銷燬Webview
    @Override
    protected void onDestroy() {
        if (mWebview != null) {
            mWebview.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            mWebview.clearHistory();

            ((ViewGroup) mWebview.getParent()).removeView(mWebview);
            mWebview.destroy();
            mWebview = null;
        }
        super.onDestroy();
    }
}



發佈了19 篇原創文章 · 獲贊 2 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章