Detailed explanation of WebViwe caching pattern

Keywords: Android Database network Java

When Html is loaded, two folders, database and cache, are generated under our data/application package:
The Url record we requested is stored in webviewCache.db, and the content of the URL is stored in the webviewCache folder.

There are two caches in WebView: Web data caching (storing opened pages and resources) and H5 caching (AppCache).


I. Web Cache

1. Cache Composition
/data/data/package_name/cache/
/data/data/package_name/database/webview.db

/data/data/package_name/database/webviewCache.db

From the synthesis, we can know that the web view will save the url of the web page we have visited (css, pictures, js, etc.) to the web page file (css, js, etc.) data base In the table

Caching modes (5)
LOAD_CACHE_ONLY: Read only local cached data without using the network
LOAD_DEFAULT: Decides whether to retrieve data from the network based on cache-control.
LOAD_CACHE_NORMAL: API level 17 has been discarded, starting with API level 11 and working with the LOAD_DEFAULT model
LOAD_NO_CACHE: Do not use caching, only get data from the network.
LOAD_CACHE_ELSE_NETWORK uses the data in the cache whenever it is locally available, whether it expires or no-cache.
For example, the cache-control of www.taobao.com is no-cache. In the mode of LOAD_DEFAULT, data will be retrieved from the network in any case. If there is no network, there will be an error page. In the mode of LOAD_CACHE_ELSE_NETWORK, whether there is a network or not, as long as there is a local cache, the cache will be used. When there is no local cache, it is retrieved from the network.
The cache-control of www.360.com.cn is max-age=60, using local caching data in both modes.


Summary: According to the above two modes, it is suggested that the caching strategy is to determine whether there is a network or not. In some cases, LOAD_DEFAULT is used and LOAD_CACHE_ELSE_NETWORK is used when there is no network.


Setting WebView Caching Mode

private void initWebView() {    
            
        mWebView.getSettings().setJavaScriptEnabled(true);    
        mWebView.getSettings().setRenderPriority(RenderPriority.HIGH);    
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);  //Setting Cache Mode    
        // Turn on the DOM storage API function    
        mWebView.getSettings().setDomStorageEnabled(true);    
        //Turn on the database storage API function    
        mWebView.getSettings().setDatabaseEnabled(true);     
        String cacheDirPath = getFilesDir().getAbsolutePath()+APP_CACAHE_DIRNAME;    
//      String cacheDirPath = getCacheDir().getAbsolutePath()+Constant.APP_DB_DIRNAME;    
        Log.i(TAG, "cacheDirPath="+cacheDirPath);    
        //Setting up the database cache path    
        mWebView.getSettings().setDatabasePath(cacheDirPath);    
        //Setting up the Application Caches cache directory    
        mWebView.getSettings().setAppCachePath(cacheDirPath);    
        //Open Application Caches    
        mWebView.getSettings().setAppCacheEnabled(true);    
    }    

Clear cache

/**  
     * Clear WebView Cache  
     */    
    public void clearWebViewCache(){    
            
        //Clean up the Webview cache database    
        try {    
            deleteDatabase("webview.db");     
            deleteDatabase("webviewCache.db");    
        } catch (Exception e) {    
            e.printStackTrace();    
        }    
            
        //WebView Cache Files    
        File appCacheDir = new File(getFilesDir().getAbsolutePath()+APP_CACAHE_DIRNAME);    
        Log.e(TAG, "appCacheDir path="+appCacheDir.getAbsolutePath());    
            
        File webviewCacheDir = new File(getCacheDir().getAbsolutePath()+"/webviewCache");    
        Log.e(TAG, "webviewCacheDir path="+webviewCacheDir.getAbsolutePath());    
            
        //Delete the webview cache directory    
        if(webviewCacheDir.exists()){    
            deleteFile(webviewCacheDir);    
        }    
        //Delete the webview cache directory    
        if(appCacheDir.exists()){    
            deleteFile(appCacheDir);    
        }    
    }    


Complete code

package com.example.webviewtest;    
    
import java.io.File;    
    
import android.app.Activity;    
import android.graphics.Bitmap;    
import android.os.Bundle;    
import android.util.Log;    
import android.view.View;    
import android.webkit.JsPromptResult;    
import android.webkit.JsResult;    
import android.webkit.WebChromeClient;    
import android.webkit.WebSettings;    
import android.webkit.WebSettings.RenderPriority;    
import android.webkit.WebView;    
import android.webkit.WebViewClient;    
import android.widget.RelativeLayout;    
import android.widget.TextView;    
import android.widget.Toast;    
    
public class MainActivity extends Activity {    
    
    private static final String TAG = MainActivity.class.getSimpleName();    
    private static final String APP_CACAHE_DIRNAME = "/webcache";    
    private TextView tv_topbar_title;    
    private RelativeLayout rl_loading;    
    private WebView mWebView;    
    private String url;    
    
    @Override    
    protected void onCreate(Bundle savedInstanceState) {    
        super.onCreate(savedInstanceState);    
        setContentView(R.layout.activity_main);    
            
        //url:http://m.dianhua.cn/detail/31ccb426119d3c9eaa794df686c58636121d38bc?apikey=jFaWGVHdFVhekZYWTBWV1ZHSkZOVlJWY&app=com.yulore.yellowsdk_ios&uid=355136051337627    
        url = "http://m.dianhua.cn/detail/31ccb426119d3c9eaa794df686c58636121d38bc?apikey=jFaWGVHdFVhekZYWTBWV1ZHSkZOVlJWY&app=com.yulore.yellowsdk_ios&uid=355136051337627";    
        findView();    
    }    
    
    private void findView() {    
            
        tv_topbar_title = (TextView) findViewById(R.id.tv_topbar_title);    
            
        rl_loading = (RelativeLayout) findViewById(R.id.rl_loading);    
            
        mWebView = (WebView) findViewById(R.id.mWebView);    
            
        initWebView();    
            
        mWebView.setWebViewClient(new WebViewClient() {    
    
            @Override    
            public void onLoadResource(WebView view, String url) {    
                    
                Log.i(TAG, "onLoadResource url="+url);    
                    
                super.onLoadResource(view, url);    
            }    
    
            @Override    
            public boolean shouldOverrideUrlLoading(WebView webview, String url) {    
    
                Log.i(TAG, "intercept url="+url);    
                    
                webview.loadUrl(url);    
    
                return true;    
            }    
    
            @Override    
            public void onPageStarted(WebView view, String url, Bitmap favicon) {    
                    
                Log.e(TAG, "onPageStarted");    
                    
                rl_loading.setVisibility(View.VISIBLE); // Display loading interface    
            }    
    
            @Override    
            public void onPageFinished(WebView view, String url) {    
    
                String title = view.getTitle();    
    
                Log.e(TAG, "onPageFinished WebView title=" + title);    
    
                tv_topbar_title.setText(title);    
                tv_topbar_title.setVisibility(View.VISIBLE);    
    
                rl_loading.setVisibility(View.GONE); // Hidden loading interface    
            }    
    
            @Override    
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {    
    
                rl_loading.setVisibility(View.GONE); // Hidden loading interface    
    
                Toast.makeText(getApplicationContext(), "",    
                        Toast.LENGTH_LONG).show();    
            }    
        });    
    
        mWebView.setWebChromeClient(new WebChromeClient() {    
    
            @Override    
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {    
    
                Log.e(TAG, "onJsAlert " + message);    
    
                Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();    
    
                result.confirm();    
    
                return true;    
            }    
    
            @Override    
            public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {    
    
                Log.e(TAG, "onJsConfirm " + message);    
    
                return super.onJsConfirm(view, url, message, result);    
            }    
    
            @Override    
            public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {    
    
                Log.e(TAG, "onJsPrompt " + url);    
    
                return super.onJsPrompt(view, url, message, defaultValue, result);    
            }    
        });    
            
        mWebView.loadUrl(url);    
    }    
    
    private void initWebView() {    
            
        mWebView.getSettings().setJavaScriptEnabled(true);    
        mWebView.getSettings().setRenderPriority(RenderPriority.HIGH);    
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);  //Setting Cache Mode    
        // Turn on the DOM storage API function    
        mWebView.getSettings().setDomStorageEnabled(true);    
        //Turn on the database storage API function    
        mWebView.getSettings().setDatabaseEnabled(true);     
        String cacheDirPath = getFilesDir().getAbsolutePath()+APP_CACAHE_DIRNAME;    
//      String cacheDirPath = getCacheDir().getAbsolutePath()+Constant.APP_DB_DIRNAME;    
        Log.i(TAG, "cacheDirPath="+cacheDirPath);    
        //Setting up the database cache path    
        mWebView.getSettings().setDatabasePath(cacheDirPath);    
        //Setting up the Application Caches cache directory    
        mWebView.getSettings().setAppCachePath(cacheDirPath);    
        //Open Application Caches    
        mWebView.getSettings().setAppCacheEnabled(true);    
    }    
        
    /**  
     * Clear WebView Cache  
     */    
    public void clearWebViewCache(){    
            
        //Clean up the Webview cache database    
        try {    
            deleteDatabase("webview.db");     
            deleteDatabase("webviewCache.db");    
        } catch (Exception e) {    
            e.printStackTrace();    
        }    
            
        //WebView Cache Files    
        File appCacheDir = new File(getFilesDir().getAbsolutePath()+APP_CACAHE_DIRNAME);    
        Log.e(TAG, "appCacheDir path="+appCacheDir.getAbsolutePath());    
            
        File webviewCacheDir = new File(getCacheDir().getAbsolutePath()+"/webviewCache");    
        Log.e(TAG, "webviewCacheDir path="+webviewCacheDir.getAbsolutePath());    
            
        //Delete the webview cache directory    
        if(webviewCacheDir.exists()){    
            deleteFile(webviewCacheDir);    
        }    
        //Delete the webview cache directory    
        if(appCacheDir.exists()){    
            deleteFile(appCacheDir);    
        }    
    }    
        
    /**  
     * Remove files/folders recursively  
     *   
     * @param file  
     */    
    public void deleteFile(File file) {    
    
        Log.i(TAG, "delete file path=" + file.getAbsolutePath());    
            
        if (file.exists()) {    
            if (file.isFile()) {    
                file.delete();    
            } else if (file.isDirectory()) {    
                File files[] = file.listFiles();    
                for (int i = 0; i < files.length; i++) {    
                    deleteFile(files[i]);    
                }    
            }    
            file.delete();    
        } else {    
            Log.e(TAG, "delete file no exists " + file.getAbsolutePath());    
        }    
    }    
    
}    




Posted by FidelGonzales on Fri, 29 Mar 2019 12:03:28 -0700