Android WebView 詳解


一、緩存:
在assets文件夾下添加index.html,里面有一個img標簽獲取圖片!

<img alt="圖片"
src="https://images0.cnblogs.com/blog/391137/201304/18081911-50a2631f6af343d5b3444cb0e0454ff9.jpg">

MainActivity:

public class MainActivity extends Activity {
    private WebView webview;
    private static String url = "file:///android_asset/index.html";

    public void getcache(View v) { // 點擊獲取緩存數據
        ImageView iv = new ImageButton(MainActivity.this);
        iv.setImageBitmap(getPictureFromCache());
        Dialog dig = new Dialog(MainActivity.this);
        dig.setTitle("圖片");
        dig.setContentView(iv);
        dig.show();
    }
private Bitmap getPictureFromCache() { Bitmap bitmap = null; File file = new File(getCacheDir() + "/webviewCacheChromium/f_000001"); try { FileInputStream ins = new FileInputStream(file); bitmap = BitmapFactory.decodeStream(ins); } catch (FileNotFoundException e) { e.printStackTrace(); } return bitmap; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); webview = (WebView) findViewById(R.id.webview); webview.loadUrl(url); } }

第一次打開應用之后可以看到File Explorer中cache文件夾下多了一些文件;

getPictureFromCache()方法中地址來源:getCacheDir()方法返回cache文件夾,通過index.html頁面中的圖片地址獲取圖片知道圖片大小為57159kb,對應的數據即為/webviewCacheChromium/f_000001

二、WebView使用簡單設置

    private void setSettings() {
        WebSettings settings = webview.getSettings();
        settings.setJavaScriptEnabled(true);// 這樣網頁就可加載JavaScript了
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        webview.setWebViewClient(new WebViewClient());// 設置點擊網頁中的鏈接不會打開android內置的瀏覽器,默認情況下點擊鏈接會打開android內置的瀏覽器
        settings.setBuiltInZoomControls(true);// 顯示放大縮小按鈕
        settings.setSupportZoom(true);// 允許放大縮小
        settings.setSupportMultipleWindows(true);
    }

WebView在默認情況下會記錄訪問過的page,這樣可以實現訪問過的網頁的向前和向后瀏覽
setWebViewClient時,可以自定義WebViewClient,重寫里面的方法shouldOverrideUrlLoading

private class MyWebViewClient extends WebViewClient {
     @Override
     public boolean shouldOverrideUrlLoading(WebView view, String url) {
         if (Uri.parse(url).getHost().equals("blog.csdn.net")) {
             // 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所加載的網頁的title,有什么方法能獲取這個title呢,查看WebViewClient;

發現並沒有相關的方法;那么該如何實現?
查看webView的其它方法?發現有個setWebChromeClient,它有兩個相關的方法用於獲取Title和Icon;

        webview.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onReceivedTitle(WebView view, String title) { // 獲取到Title super.onReceivedTitle(view, title);
            }
@Override
public void onReceivedIcon(WebView view, Bitmap icon) { // 獲取到圖標 super.onReceivedIcon(view, icon); } });

通過查看網上的相關資料,還有另一種可行的方法,此種方法需要用到js與webview的交互的技術,下面是一個例子;

    public void getTitle(WebView wv) {
        wv.addJavascriptInterface(new GetTitle(), "getTitle"); // 向webview注冊一個本地接口
        wv.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                view.loadUrl("javascript:window.getTitle.onGetTitle("
                        + "document.getElementsByTagName('title')[0].innerHTML" + ");");
                super.onPageFinished(view, url);
            }
        });
    }

    class GetTitle {
        public void onGetTitle(String title) {
            // ...參數title即為網頁的標題,可在這里面進行相應的title的處理
        }
    }

 延伸思考:將上面document.getElementsByTagName('title')[0].innerHTML,將title換為其它的,就可以獲取到其它的內容;

三、WebView中應用HTML5
WebView中應用HTML5主要有三種常用情況
>>1.HTML5本地存儲

        String dir = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
        settings.setDatabaseEnabled(true);
        settings.setDatabasePath(dir);// 設置數據庫路徑
        settings.setDomStorageEnabled(true);// 使用LocalStorage則必須打開

>>2.HTML5地理位置服務,需要在設置中進行設置,另外還需要重寫WebChromeClient的允許獲取地理位置的方法;

        settings.setGeolocationEnabled(true); // 啟用地理定位
        settings.setGeolocationDatabasePath(dir); // 設置定位的數據庫路徑

重寫WebChromeClient的onGeolocationPermissionsShowPrompt方法,用於允許瀏覽器獲取地下位置;

            @Override
            public void onGeolocationPermissionsShowPrompt(String origin, Callback callback) {
                super.onGeolocationPermissionsShowPrompt(origin, callback);
                callback.invoke(origin, true, false);
            }

下面是callback.invoke方法的描述

    /**一個允許讓應用程序獲取地理位置的接口
     */
    public interface Callback {
        /**
         * Sets the Geolocation permission state for the supplied origin.
         *
         * @param origin the origin for which permissions are set
         * @param allow 是否讓origin也就是web站點獲取地理位置
         * @param retain 是否保持此權限
         */
        public void invoke(String origin, boolean allow, boolean retain);
    };

>>3.HTML5離線存儲

        settings.setAppCacheEnabled(true);// 開啟應用程序緩存
        String cache_dir = this.getApplicationContext().getDir("cache", Context.MODE_PRIVATE).getPath();
        settings.setAppCachePath(cache_dir);// 設置應用緩存的路徑
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);// 設置緩存的模式
        settings.setAppCacheMaxSize(1024 * 1024 * 8);// 設置應用緩存的最大尺寸
        settings.setAllowFileAccess(true);// 可以讀取文件緩存(manifest生效)

>>4.HTML5處理網頁中的對話框,需要重寫下面的三個方法,分別是{"警告","確認","提示"}

            @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);
            }

>>5.有時候希望使本地存儲或離線存儲的空間更大,需要擴展存儲空間,需要重寫WebChromeClient的onExceededDatabasseQuota方法;

            @Override
            public void onExceededDatabaseQuota(String url,
                    String databaseIdentifier, long quota,
                    long estimatedDatabaseSize, long totalQuota,
                    QuotaUpdater quotaUpdater) {
                super.onExceededDatabaseQuota(url, databaseIdentifier, quota,
                        estimatedDatabaseSize, totalQuota, quotaUpdater);
                quotaUpdater.updateQuota(estimatedDatabaseSize * 2); // 此方法擴展存儲空間為默認的2倍
            }

參考文章:
1.html5 webview的本地存儲優化
2.android WebView加載html5介紹
3.http://stackoverflow.com/questions/15768837/playing-html5-video-on-fullscreen-in-android-webview


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM