Android WebView離線緩存 WebViewAssetLoader 的使用

前言 :

各位同學大家好送爸,最近很長時間沒有更新文章了。因為搬到新家去了 所以留給自己的時間非常的少暖释,今天因為在項目開發(fā)上面遇到一些問題 所以就想記錄分享出來袭厂。

問題原因

是這樣的,項目組這邊做了一個安卓WebView 嵌套H5鏈接的游戲殼包 球匕。相信很多同學做過類似的需求
很多同學會說這個很簡單 初始化webview控件 然后 設置webviewsetting 即可 最后調用 xWalkView.loadUrl(url); 方法即可 因為我們加載的一個H5游戲 在初始化加載進度條的時候有一個下載動作 非常的吃網速 所以我們想到用webview 離線緩存來加載一些本地的js和圖片資源纹磺。

需要用到的三方庫

 implementation "androidx.webkit:webkit:1.2.0"

|## 具體實現(xiàn):
布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000000"
    >
    <WebView
        android:id="@+id/wv"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

布局就一個簡單的webview 然后我們 看下具體實現(xiàn)

  xWalkView = (WebView) findViewById(R.id.wv);
        WebSettings webSetting = xWalkView.getSettings();
        webSetting.setJavaScriptEnabled(true);
        webSetting.setJavaScriptCanOpenWindowsAutomatically(true);
//        webSetting.setAllowFileAccess(true);
//        webSetting.setLayoutAlgorithm(LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setSupportZoom(true);
        webSetting.setBuiltInZoomControls(true);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(true);
        // webSetting.setLoadWithOverviewMode(true);
        webSetting.setAppCacheEnabled(true);
        // webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setGeolocationEnabled(true);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        // webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSetting.setCacheMode(WebSettings.LOAD_NO_CACHE);

        webSetting.setAllowFileAccessFromFileURLs(false);
        // Off by default, deprecated for SDK versions >= 30.
        webSetting.setAllowUniversalAccessFromFileURLs(false);
        // Keeping these off is less critical but still a good idea, especially if your app is not
        // using file:// or content:// URLs.
        webSetting.setAllowFileAccess(true);
        webSetting.setAllowContentAccess(true);

為了減少網絡訪問的流量,以及提升在弱網絡或無網絡情況下的體驗亮曹,需要對網絡訪問的圖片進行本地緩存橄杨。
原先采用的是 WebView 自帶的緩存機制來實現(xiàn)秘症,但并不可靠,于是需要通過攔截網絡請求式矫,通過本地緩存干預的方式來實現(xiàn)乡摹。具體原理如下:
我們看下官方的介紹


image.png
final WebViewAssetLoader assetLoader = new WebViewAssetLoader.Builder()
           .addPathHandler("/assets/", new AssetsPathHandler(this))
           .build();
 
  webView.setWebViewClient(new WebViewClient() {
      @Override
      @RequiresApi(21)
      public WebResourceResponse shouldInterceptRequest(WebView view,
                                       WebResourceRequest request) {
          return assetLoader.shouldInterceptRequest(request.getUrl());
      }
 
      @Override
      @SuppressWarnings("deprecation") // for API < 21
      public WebResourceResponse shouldInterceptRequest(WebView view,
                                       WebResourceRequest request) {
          return assetLoader.shouldInterceptRequest(Uri.parse(request));
      }
  });
 
  WebSettings webViewSettings = webView.getSettings();
  // Setting this off for security. Off by default for SDK versions >= 16.
  webViewSettings.setAllowFileAccessFromFileURLs(false);
  // Off by default, deprecated for SDK versions >= 30.
  webViewSettings.setAllowUniversalAccessFromFileURLs(false);
  // Keeping these off is less critical but still a good idea, especially if your app is not
  // using file:// or content:// URLs.
  webViewSettings.setAllowFileAccess(false);
  webViewSettings.setAllowContentAccess(false);
 
  // Assets are hosted under http(s)://appassets.androidplatform.net/assets/... .
  // If the application's assets are in the "main/assets" folder this will read the file
  // from "main/assets/www/index.html" and load it as if it were hosted on:
  // https://appassets.androidplatform.net/assets/www/index.html
  webview.loadUrl("https://appassets.androidplatform.net/assets/www/index.html");

我們在官方代碼里面可以看到官方提供了不同系統(tǒng)版本的 shouldInterceptRequest 回調方法里面的處理方式 api>=21和 api<21 的放到今天我們基本不用考慮 api<21 的情況 哈哈

具體實現(xiàn)

  final WebViewAssetLoader assetLoader = new WebViewAssetLoader.Builder()
               .setDomain("js遠程訪問域名")
                .addPathHandler("/", new WebViewAssetLoader.AssetsPathHandler(this))
                .build();
        xWalkView.loadUrl(url);
        xWalkView.setWebViewClient(new WebViewClient(){
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView webView, WebResourceRequest request) {
                //if (request.getUrl().toString().contains("main.min.js")) {
                MKDebug.log(request.getUrl().toString());
                if (request.getUrl().toString().contains(".js")) {
                    MKDebug.log("....");
                    Log.e(TAG, "shouldInterceptRequest:request.getUrl()  -- > " + request.getUrl());
                    try {
                        WebResourceResponse obj = assetLoader.shouldInterceptRequest(request.getUrl());
                        if (obj != null) {
                            Log.e(TAG, "shouldInterceptRequest: obj  --- >   " + obj);
                            Map headers = new HashMap<>();
                            headers.put("Access-Control-Allow-Origin", "*");
                            headers.put("Access-Control-Allow-Headers", "X-Requested-With");
                            headers.put("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
                            headers.put("Access-Control-Allow-Credentials", "true");
                            String pp = request.getUrl().getPath();
                            String path = removeLeadingSlash(pp);
                            String mimeType = guessMimeType(path);
                            StringBuffer stringBuffer = new StringBuffer();
                            BufferedReader bufferedReader = null;
                            Log.e(TAG, "shouldInterceptRequest: " + obj.getData());
                            bufferedReader = new BufferedReader(new InputStreamReader(obj.getData()));
                            String line = "";
                            try {
                                while ((line = bufferedReader.readLine()) != null) {
                                    stringBuffer.append(line);
                                    if (line.equals("<head>")) {
                                        // 在<head>中添加<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
                                        stringBuffer.append("<meta http-equiv=\"Content-Security-Policy\" content=\"upgrade-insecure-requests\">");
                                    }
                                }
                            } catch (Exception e) {
                            }
                            WebResourceResponse response = new WebResourceResponse(mimeType,
                                    "utf-8", 200, "OK", headers,
                                    new ByteArrayInputStream(stringBuffer.toString().getBytes()));
                            MKDebug.log(response == null ? "無內容" : "有內容");
                            return response;
                        } else {
                            return null;
                        }

                    } catch (Exception e) {
                        return null;

                    }
                }else{
                    return null;
         }

這邊在 shouldInterceptRequest 回調方法里面拿到 request 對象后 我們

WebResourceResponse obj = assetLoader.shouldInterceptRequest(request.getUrl());

通過 上面的assetLoader對象調用一個shouldInterceptRequest 方法進行一個循環(huán)匹配本地資源路徑

image.png

image.png

我們通過分析源碼可以看到循環(huán)去查找本地資源匹配
image.png

因為這邊給到的本地資源不是很全
image.png

    if (request.getUrl().toString().contains(".js")) {
                    Log.e(TAG, "shouldInterceptRequest:request.getUrl()  -- > " + request.getUrl());
                    try {
                        WebResourceResponse obj = assetLoader.shouldInterceptRequest(request.getUrl());
                        if (obj != null) {
                            Log.e(TAG, "shouldInterceptRequest: obj  --- >   " + obj);
                            Map headers = new HashMap<>();
                            headers.put("Access-Control-Allow-Origin", "*");
                            headers.put("Access-Control-Allow-Headers", "X-Requested-With");
                            headers.put("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
                            headers.put("Access-Control-Allow-Credentials", "true");
                            String pp = request.getUrl().getPath();
                            String path = removeLeadingSlash(pp);
                            String mimeType = guessMimeType(path);
                            StringBuffer stringBuffer = new StringBuffer();
                            BufferedReader bufferedReader = null;
                            Log.e(TAG, "shouldInterceptRequest: " + obj.getData());
                            bufferedReader = new BufferedReader(new InputStreamReader(obj.getData()));
                            String line = "";
                            try {
                                while ((line = bufferedReader.readLine()) != null) {
                                    stringBuffer.append(line);
                                    if (line.equals("<head>")) {
                                        // 在<head>中添加<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
                                        stringBuffer.append("<meta http-equiv=\"Content-Security-Policy\" content=\"upgrade-insecure-requests\">");
                                    }
                                }
                            } catch (Exception e) {
                            }
                            WebResourceResponse response = new WebResourceResponse(mimeType,
                                    "utf-8", 200, "OK", headers,
                                    new ByteArrayInputStream(stringBuffer.toString().getBytes()));
                            MKDebug.log(response == null ? "無內容" : "有內容");
                            return response;
                        } else {
                            return null;
                        }

                    } catch (Exception e) {
                        return null;

                    }
                }else{
                    return null;
                }
   所以我們只判斷包含.js的文件其余的我們不處理 然后圖片這邊處理有點問題 我直接簡單粗暴的try catch捕獲異常處理了 包沒有崩潰  最后效果是加了webview離線緩存包確實比沒有處理的好加載快很多 因為有部分的js用的assets目錄下的資源 .

最后總結 :

這次處理這個項目 我也是一臉懵 跟cp合作公司那邊對接過技術方案 那邊直接是用三方處理的 我們這邊技術負責人 自己就看了官方代碼自己實現(xiàn)了 。最后還是有人協(xié)助解決掉了 所提記錄下 希望能幫助到各位網友 采转。 最后希望我的文章能幫助到各位解決問題 聪廉,以后我還會貢獻更多有用的代碼分享給大家。各位同學如果覺得文章還不錯 氏义,麻煩給關注和star锄列,小弟在這里謝過啦!
官方介紹 WebViewAssetLoader 地址:
https://developer.android.google.cn/reference/kotlin/androidx/webkit/WebViewAssetLoader

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市惯悠,隨后出現(xiàn)的幾起案子邻邮,更是在濱河造成了極大的恐慌,老刑警劉巖克婶,帶你破解...
    沈念sama閱讀 217,406評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件筒严,死亡現(xiàn)場離奇詭異,居然都是意外死亡情萤,警方通過查閱死者的電腦和手機鸭蛙,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,732評論 3 393
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來筋岛,“玉大人娶视,你說我怎么就攤上這事≌鲈祝” “怎么了肪获?”我有些...
    開封第一講書人閱讀 163,711評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長柒傻。 經常有香客問我孝赫,道長,這世上最難降的妖魔是什么红符? 我笑而不...
    開封第一講書人閱讀 58,380評論 1 293
  • 正文 為了忘掉前任青柄,我火速辦了婚禮,結果婚禮上预侯,老公的妹妹穿的比我還像新娘致开。我一直安慰自己昧互,他們只是感情好孟害,可當我...
    茶點故事閱讀 67,432評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著妆距,像睡著了一般校坑。 火紅的嫁衣襯著肌膚如雪拣技。 梳的紋絲不亂的頭發(fā)上千诬,一...
    開封第一講書人閱讀 51,301評論 1 301
  • 那天,我揣著相機與錄音膏斤,去河邊找鬼徐绑。 笑死,一個胖子當著我的面吹牛莫辨,可吹牛的內容都是我干的傲茄。 我是一名探鬼主播,決...
    沈念sama閱讀 40,145評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼沮榜,長吁一口氣:“原來是場噩夢啊……” “哼盘榨!你這毒婦竟也來了?” 一聲冷哼從身側響起蟆融,我...
    開封第一講書人閱讀 39,008評論 0 276
  • 序言:老撾萬榮一對情侶失蹤草巡,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后型酥,有當地人在樹林里發(fā)現(xiàn)了一具尸體山憨,經...
    沈念sama閱讀 45,443評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,649評論 3 334
  • 正文 我和宋清朗相戀三年弥喉,在試婚紗的時候發(fā)現(xiàn)自己被綠了郁竟。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,795評論 1 347
  • 序言:一個原本活蹦亂跳的男人離奇死亡由境,死狀恐怖棚亩,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情虏杰,我是刑警寧澤蔑舞,帶...
    沈念sama閱讀 35,501評論 5 345
  • 正文 年R本政府宣布,位于F島的核電站嘹屯,受9級特大地震影響,放射性物質發(fā)生泄漏从撼。R本人自食惡果不足惜州弟,卻給世界環(huán)境...
    茶點故事閱讀 41,119評論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望低零。 院中可真熱鬧婆翔,春花似錦、人聲如沸掏婶。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,731評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽雄妥。三九已至最蕾,卻和暖如春依溯,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背瘟则。 一陣腳步聲響...
    開封第一講書人閱讀 32,865評論 1 269
  • 我被黑心中介騙來泰國打工黎炉, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人醋拧。 一個月前我還...
    沈念sama閱讀 47,899評論 2 370
  • 正文 我出身青樓慷嗜,卻偏偏與公主長得像,于是被迫代替她去往敵國和親丹壕。 傳聞我的和親對象是個殘疾皇子庆械,可洞房花燭夜當晚...
    茶點故事閱讀 44,724評論 2 354