WebView的用法

來源:互聯網
上載者:User

標籤:許可權   ini   received   技術   電話   bundle   rmi   relative   打電話   

基本用法

布局檔案配置WebView

          <WebView            android:id="@+id/wv_news_detail"            android:layout_width="match_parent"            android:layout_height="match_parent" />

WebView載入網頁
      

     //載入網頁連結        mWebView.loadUrl("http://www.itheima.com");        //載入本地assets目錄下的網頁        mWebView.loadUrl("file:///android_asset/demo.html");

WebView基本設定

        WebSettings settings = mWebView.getSettings();        settings.setBuiltInZoomControls(true);// 顯示縮放按鈕(wap網頁不支援)        settings.setUseWideViewPort(true);// 支援雙擊縮放(wap網頁不支援)        settings.setJavaScriptEnabled(true);// 支援js功能

設定WebViewClient

     

  mWebView.setWebViewClient(new WebViewClient() {            // 開始載入網頁            @Override            public void onPageStarted(WebView view, String url, Bitmap favicon) {                super.onPageStarted(view, url, favicon);                System.out.println("開始載入網頁了");            }            // 網頁載入結束            @Override            public void onPageFinished(WebView view, String url) {                super.onPageFinished(view, url);                System.out.println("網頁載入結束");            }            // 所有連結跳轉會走此方法            @Override            public boolean shouldOverrideUrlLoading(WebView view, String url) {                System.out.println("跳轉連結:" + url);                view.loadUrl(url);// 在跳轉連結時強制在當前webview中載入                //此方法還有其他應用情境, 比如寫一個超連結<a href="tel:110">聯絡我們</a>, 當點擊該超連結時,可以在此方法中擷取連結地址tel:110,               //解析該地址,擷取電話號碼, 然後跳轉到本地打電話頁面, 而不是載入網頁, 從而實現了webView和本地代碼的互動                return true;            }        });

設定WebChromeClient

 mWebView.setWebChromeClient(new WebChromeClient() {            @Override            public void onProgressChanged(WebView view, int newProgress) {                super.onProgressChanged(view, newProgress);                // 進度發生變化                System.out.println("進度:" + newProgress);            }            @Override            public void onReceivedTitle(WebView view, String title) {                super.onReceivedTitle(view, title);                // 網頁標題                System.out.println("網頁標題:" + title);            }        });

WebView載入上一頁和下一頁

mWebView.goBack();//跳到上個頁面 mWebView.goForward();//跳到下個頁面 mWebView.canGoBack();//是否可以跳到上一頁(如果返回false,說明已經是第一頁) mWebView.canGoForward();//是否可以跳到下一頁(如果返回false,說明已經是最後一頁)

 

WebView進階用法

緩衝設定 

    WebSettings settings = mWebView.getSettings();        //只要本地有,無論是否到期,或者no-cache,都使用緩衝中的資料        settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);        //只載入緩衝        settings.setCacheMode(WebSettings.LOAD_CACHE_ONLY);        //根據cache-control決定是否從網路上取資料        settings.setCacheMode(WebSettings.LOAD_DEFAULT);        //不載入緩衝        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);    

什麼是cache-control?

        cache-control是在請求網頁時伺服器的回應標頭,此回應標頭用於決定網頁的緩衝策略.       

   常見的取值有public(所有內容都將被緩衝), private(內容只緩衝到私人緩衝中),no-cache(所有內容都不會被緩衝),max-age=xxx(緩衝的內容將在 xxx 秒後失效)等等

 :




清理緩衝

   最簡便的方式:        mWebView.clearCache(true);        另外一種方式:        //刪除快取檔案夾        File file = CacheManager.getCacheFileBaseDir();            if (file != null && file.exists() && file.isDirectory()) {             for (File item : file.listFiles()) {              item.delete();             }             file.delete();            }         //刪除快取資料庫        context.deleteDatabase("webview.db");         context.deleteDatabase("webviewCache.db");

Cookie設定

        CookieSyncManager.createInstance(this);        CookieManager cookieManager = CookieManager.getInstance();        cookieManager.setAcceptCookie(true);        String cookie = "name=xxx;age=18";        cookieManager.setCookie(URL, cookie);        CookieSyncManager.getInstance().sync();

擷取Cookie

        CookieManager cookieManager = CookieManager.getInstance();        String cookie = cookieManager.getCookie(URL);

清除Cookie

        CookieSyncManager.createInstance(context);          CookieManager cookieManager = CookieManager.getInstance();         cookieManager.removeAllCookie();        CookieSyncManager.getInstance().sync();

Demo示範:

package com.loaderman.webviewdemo;import android.graphics.Bitmap;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.webkit.WebChromeClient;import android.webkit.WebSettings;import android.webkit.WebView;import android.webkit.WebViewClient;public class MainActivity extends AppCompatActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        WebView mWebView = (WebView) findViewById(R.id.wv_test);        //載入網頁連結        mWebView.loadUrl("http://www.baidu.com");        //載入本地assets目錄下的網頁        //mWebView.loadUrl("file:///android_asset/demo.html");        WebSettings settings = mWebView.getSettings();        settings.setBuiltInZoomControls(true);// 顯示縮放按鈕(wap網頁不支援)        settings.setUseWideViewPort(true);// 支援雙擊縮放(wap網頁不支援)        settings.setJavaScriptEnabled(true);// 支援js功能        mWebView.setWebChromeClient(new WebChromeClient() {            @Override            public void onProgressChanged(WebView view, int newProgress) {                super.onProgressChanged(view, newProgress);                // 進度發生變化                System.out.println("進度:" + newProgress);            }            @Override            public void onReceivedTitle(WebView view, String title) {                super.onReceivedTitle(view, title);                // 網頁標題                System.out.println("網頁標題:" + title);            }        });        mWebView.setWebViewClient(new WebViewClient() {            // 開始載入網頁            @Override            public void onPageStarted(WebView view, String url, Bitmap favicon) {                super.onPageStarted(view, url, favicon);                System.out.println("開始載入網頁了");            }            // 網頁載入結束            @Override            public void onPageFinished(WebView view, String url) {                super.onPageFinished(view, url);                System.out.println("網頁載入結束");            }            // 所有連結跳轉會走此方法            @Override            public boolean shouldOverrideUrlLoading(WebView view, String url) {                System.out.println("跳轉連結:" + url);                view.loadUrl(url);// 在跳轉連結時強制在當前webview中載入                //此方法還有其他應用情境, 比如寫一個超連結<a href="tel:110">聯絡我們</a>, 當點擊該超連結時,可以在此方法中擷取連結地址tel:110,          //解析該地址,擷取電話號碼, 然後跳轉到本地打電話頁面, 而不是載入網頁, 從而實現了webView和本地代碼的互動                return true;            }        });    }}

 activity_main.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayout    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/activity_main"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="com.loaderman.webviewdemo.MainActivity">    <WebView        android:id="@+id/wv_test"        android:layout_width="match_parent"        android:layout_height="match_parent" /></RelativeLayout>

 添加網路許可權:

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

 :

運行就直接開啟網頁百度首頁面

直接看日誌:

 

WebView的應用情境

  WebView的應用情境我們無需多講, 此處我只提一點: 隨著html5的普及, 很多app都會內嵌webview來載入html5頁面, 而且h5做的和app原生控制項極其相似, 那麼我們如何辨認某個頁面使用h5做的還是用原生控制項做的呢?
  開啟開發人員選項, 你會看到這樣一個選項:顯示布局邊界

勾選之後,所有原生控制項布局的邊框都會顯示出來

我們現在在這種狀態下開啟一個WebView看一眼(這是錢包-滴滴出行的頁面)

如果是WebView的話, 只有在WebView邊緣才會顯示一個邊框, WebView內部是沒有邊框的;如果是原生控制項,怎麼可能邊框這麼少呢? 從而我們可以斷定,的滴滴出行頁面一定是用WebView載入網頁實現的, 而不是系統原生控制項.

 

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.