簡談WebViewClient與WebChromeClient

來源:互聯網
上載者:User

標籤:

簡介:WebViewClient被用來傳遞單純的載入一個連結時所發生的事件,比如開始載入,結束載入等,它代表這個連結載入時的最普通的和最籠統的事件,WebChromeClient更多的是傳遞JS對話方塊,上傳檔案,網頁的標題改變等網頁內元素的事件。

 

 

 一,WebViewClient

 

     

  1. 下面介紹下幾個簡單的應用:

         

  •        使用我們自己的WebView載入頁面上的連結

               當使用者點擊一個網頁上的串連時,預設的操作是另外開啟一個與之相關的應用然後傳遞URL,通常是開啟我們系統預設的瀏覽器然後載入目標URL地址。                  但是我們可以重新定義這個操作既使用我們自己的WebView開啟開啟這個URL,你還可以通過他們的瀏覽曆史允許使用者導航向前像後。能夠到達上面的效                果西需要我們提供一個自己的WebView,然後適用setWebViewClient()

 

WebView webview = f(WebView)indViewById(R.id.webview);webview.setWebViewClient(new WebViewClient());

 

               這個運行使用者使用你自己的WebView載入連結

               如果想要在點擊一個串連後擷取到更多的控制,需要我們建立我們自己的WebClient,然後重寫shouldOverrideUrlLoading() 方法,

               例如:我們如果點擊的我連結是我自己的就用我們自己的WebView載入,如果是別的連結就用別的應用開啟

 

private class MyWebViewClient extends WebViewClient {    @Override    public boolean shouldOverrideUrlLoading(WebView view, String url) {               if (Uri.parse(url).getHost().equals("www.example.com")) {            // This is my web site, so do not override; let my WebView                load  the page            return false;        }        // Otherwise, the link is not for a page on my site, so launch             another Activity that handles URLs        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));        startActivity(intent);        return true;    }}

然後:

WebView myWebView = (WebView) findViewById(R.id.webview);myWebView.setWebViewClient(new MyWebViewClient());

showOverrideUrlLoading的傳回值為false時代表我們自己的WebView會處理這個連結,如果為true代表會傳遞給系統做相應的處理(如:提供一些能夠處理這個連線應用程式讓你選擇)

 

  • 導航網頁瀏覽曆史

        當我們重寫URL載入時,它會自動的累計你的網頁瀏覽曆史,你可以通過goBack()和goForward()向前或者向後導航。

        例如:我們的Activity使用返回鍵處理返回導航

@Overridepublic boolean onKeyDown(int keyCode, KeyEvent event) {    // Check if the key event was the Back button and if there‘s history    if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {        myWebView.goBack();        return true;    }    // If it wasn‘t the Back key or there‘s no web page history, bubble up to the default    // system behavior (probably exit the activity)    return super.onKeyDown(keyCode, event);}

如果不進行這個檢查,當使用者已經瀏覽器完所有的曆史之後goBack()和goForward()將不起任何作用。

 

 

二,WebChromeClient

 

       WebChromeClient是Html/Js和Android用戶端進行互動的一個中介軟體,其將webview中js所產生的事件封裝,然後傳遞到Android用戶端。Google這樣做的其中一個很重要的原因就是安全問題。

      主要輔助WebView處理JavaScript對話方塊,載入進度,上傳檔案等。

 

1.下面是幾個常使用的案例

 

  • 使用html與Android系統互動選擇並上傳系統的檔案

         這裡有兩個方法:

        第一種:安卓用戶端遠程調用html中JS方法,js遠程調用Android用戶端方法。

        第二種:重寫WebChromeClient

        詳情請參考我的另一篇文章:http://www.cnblogs.com/ufreedom/p/4158081.html

  • 調試WebView,列印WebView處理網頁時log

         WebChromeClient處理了javascript的console的功能,js可以使用console列印調試資訊,在API 7時WebChromeClient將console資訊通過      onConsoleMessage傳遞給java層。在API8或者更高的版本中WebChromeClient將console資訊封裝成ConsoleMessage,然後通過onChromClient傳遞。

API7:

?WebView myWebView = (WebView) findViewById(R.id.webview);myWebView.setWebChromeClient(new WebChromeClient() {  public void onConsoleMessage(String message, int lineNumber, String sourceID) {    Log.d("MyApplication", message + " -- From line "                         + lineNumber + " of "                         + sourceID);  }});

 

API8或者更高:

WebView myWebView = (WebView) findViewById(R.id.webview);myWebView.setWebChromeClient(new WebChromeClient() {  public boolean onConsoleMessage(ConsoleMessage cm) {    Log.d("MyApplication", cm.message() + " -- From line "                         + cm.lineNumber() + " of "                         + cm.sourceId() );    return true;  }});

 

ConsoleMessage包含了一個MesssageLeavel 對象用來表示console資訊的類型,我們可以使用messageLevel()擷取資訊類型。

 

  • WebChromeClient彈出html中js對話方塊資訊

        我們知道WebView是無法彈出js對話方塊的,WebChromeClient封裝了js對話方塊資訊

  

        @Override        public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {            String newTitle = getTitleFromUrl(url);            new AlertDialog.Builder(DuomiWebActivity.this).setTitle(newTitle).setMessage(message)                    .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {                        @Override                        public void onClick(DialogInterface dialog, int which) {                            result.confirm();                        }                    }).setCancelable(false).create().show();            return true;        }        @Override        public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {            String newTitle = getTitleFromUrl(url);            new AlertDialog.Builder(DuomiWebActivity.this).setTitle(newTitle).setMessage(message)                    .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {                        @Override                        public void onClick(DialogInterface dialog, int which) {                            result.confirm();                        }                    }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {                        public void onClick(DialogInterface dialog, int which) {                            result.cancel();                        }                    }).setCancelable(false).create().show();            return true;        }

 

   

 

  •  添加網頁載入進度條效果

         需要我們重寫onProgressChanged(WebView view, int newProgress)方法

 

簡談WebViewClient與WebChromeClient

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.