Android Webview總結

這些都是曾經收集到的一些關于Webview的知識,有些工作中用到了,有些暫時還沒有用到,這次統一整理下,希望對自己,對大家有所幫助。另外,歡迎大家補充(當然,有錯也要指正呀,不勝感激),如果可以的話,我會 更新到本帖中。

官方文檔
更多知識:)

一.權限

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

二.創建Webview對象

WebView webview = new WebView(this);

三.加載網頁的方式

  • loadData(String data, String mimeType, String encoding)
    des:Load the given data into the WebView.
    as:
    String summary = "<html><body>You scored <b>192</b> points.</body></html>";
    webview.loadData(summary, "text/html", null);
  • loadDataWithBaseURL(String baseUrl, String data, String mimeType, String encoding, String historyUrl)
    des:Load the given data into the WebView, use the provided URL as the base URL for the content.
  • loadUrl(String url)
    des:Load the given url.
    as: webView.loadUrl("http://www.lxweimin.com/"); //加載網絡網頁
    webView.loadUrl("file:///android_asset/html/index.html"); //加載本地assert目錄下網頁
    webView.loadUrl("content://com.Android.htmlfileprovider/sdcard/kris.html"); // 加載SD卡html
  • loadUrl(String url, Map<String, String> extraHeaders)
    Load the given url with the extra headers.
  • postUrl(String url, byte[] postData)
    des: Loads the URL with postData using "POST" method into this WebView.
  • 利用Intent調用系統瀏覽器
    Uri uri = Uri.parse("http://www.lxweimin.com/");
    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    startActivity(intent);

四.設置Webview

webView.clearHistory();
webView.clearCache(true);
webView.clearFormData();
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);// 隱藏滾動條webView.requestFocus();
webView.requestFocusFromTouch();

五.Webview輔助類

1>WebSettings

設置WebView的一些屬性、狀態等,例如允許使用javascript,允許使用緩存,允許使用內置的縮放組件,設置支持IS等。

  • 官方文檔
  • 獲取WebSettings對象:
    WebSettings mWebSettings = webView.getSettings();
  • For Example
WebSettings mWebSettings = webView.getSettings();
mWebSettings.setJavaScriptEnabled(true);// 支持JS
mWebSettings.setJavaScriptCanOpenWindowsAutomatically(true);//支持通過js打開新的窗口
mWebSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);//提高渲染等級
mWebSettings.setBuiltInZoomControls(false);// 設置支持縮放
mWebSettings.setDomStorageEnabled(true);//使用localStorage則必須打開
mWebSettings.setBlockNetworkImage(true);// 首先阻塞圖片,讓圖片不顯示
mWebSettings.setBlockNetworkImage(false);//  頁面加載好以后,在放開圖片:
mWebSettings.setSupportMultipleWindows(false);// 設置同一個界面
mWebSettings.setBlockNetworkImage(false);
mWebSettings.setCacheMode(1);
mWebSettings.setNeedInitialFocus(false);// 禁止webview上面控件獲取焦點(黃色邊框)
2>WebViewClient

主要幫助WebView處理各種通知、請求事件(例如,點擊鏈接時候如何顯示界面,頁面開始加載,加載完畢之后有何動作等)

webView.setWebViewClient(new WebViewClient() {
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        //頁面開始加載時
        super.onPageStarted(view, url, favicon);
    }
    @Override
    public void onPageFinished(WebView view, String url) {
        //頁面加載結束時
        super.onPageFinished(view, url);
    }
    @Override
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        super.onReceivedError(view, errorCode, description, failingUrl);
        // 這里進行無網絡或錯誤處理,具體可以根據errorCode的值進行判斷,
    }
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        /**
         * 網頁跳轉:
         * 1.在當前的webview跳轉到新連接
         * view.loadUrl(url);
         * 2.調用系統瀏覽器跳轉到新網頁
         * Intent i = new Intent(Intent.ACTION_VIEW);
         * i.setData(Uri.parse(url));
         * startActivity(i);
         */
        return true;
    }
});
3>WebChromeClient

輔助WebView處理Javascript的對話框、網站圖標、網站Title、加載進度等

webView.setWebChromeClient(new WebChromeClient() {
    @Override
    public void onProgressChanged(WebView view, int newProgress) {
        // 獲得網頁的加載進度 newProgress為當前加載百分比
        super.onProgressChanged(view, newProgress);
    }
    @Override
    public void onReceivedTitle(WebView view, String title) {
        // 獲取網頁的title,客戶端可以在這里動態修改頁面的title
        // 另外,當加載錯誤時title為“找不到該網頁”
        super.onReceivedTitle(view, title);
    }
});

六.與JS交互addJavascriptInterface

  • 前提
mWebView.getSettings().setJavaScriptEnabled(true);  
  • 使用
mWebView.addJavascriptInterface(new JSInterface(), "jsInterface");  
JSInterface對象:
public class JSInterface {

    @JavascriptInterface
    public void methodA() {    }

    @JavascriptInterface
    public void methodB(String webMessage) {    }
}

注意:
1.JavascriptInterface是4.2版本google新增的一個注解,為了避免一個安全隱患,詳細信息及4.2以下系統版本適配看這里: Android WebView的Js對象注入漏洞解決方案 ;另外,safe-java-js-webview-bridge這個開源項目完全用onJsPrompt() 替代了addJavaScriptInterface(),有興趣的可以學習。
2.JS調用Java:

window.js_callback.viewPicOnJavascript($('article img').index(this));

3.客戶端調用JS

mWebView.loadUrl("javascript:alert()");

七.鍵盤

  • webview是否可以返回到上一頁面 webView.canGoBack()
  • webview返回到上一頁面 webView.goBack();
  • webview是否可以前進 webView.canGoForward()
  • webview前進 webView.goForward();
public boolean onKeyDown(int keyCode, KeyEvent event) {
     if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
         mWebView.goBack();
         return true;
     }
     return super.onKeyDown(keyCode, event);
 }

八.其他

  • WebViewFragment
    好吧,之前確實不知道有這么個東東,今天寫這篇貼子的時候才發現的,看名字,應該是在Fragment里對Webview的封裝,應該是個好東西。有興趣的小伙伴們 點進來:WebViewFragment
  • WebView cookies清理
CookieSyncManager.createInstance(this);
CookieSyncManager.getInstance().startSync();
CookieManager.getInstance().removeSessionCookie();
  • 屏蔽長按事件
webView.setOnLongClickListener(new View.OnLongClickListener() {
    @Override
    public boolean onLongClick(View v) {
        return true;
    }
});
  • Webiew保留縮放功能但是隱藏縮放控件(這是一招必殺技)
webView.getSettings().setSupportZoom(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDisplayZoomControls(false);
// setDisplayZoomControls是在Android 3.0中新增的API.,調用此方法前需要對系統版本進行判斷
  • 判斷Webview是否滑動到頂部或底部
if (webView.getContentHeight() * webView.getScale() == (webView.getHeight() + webView.getScrollY())) {
    // 處于底端
}
if(webView.getScrollY() == 0){
    //處于頂部
}
des:
getScrollY() //方法返回的是當前可見區域的頂端距整個頁面頂端的距離,也就是當前內容滾動的距離.
getHeight()或者getBottom() //方法都返回當前WebView這個容器的高度
getContentHeight()返回的是整個html的高度,但并不等同于當前整個頁面的高度,因為WebView有縮放功能,所以當前整個頁面的高度實際上應該是原始html的高度再乘上縮放比例

更多內容請關注 我的專題
轉載請注明 出處:
http://www.lxweimin.com/users/c1b4a5542220/latest_articles

Thank you and have a nice weekend!

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容