Android WebView implements caching web page data

There are two kinds of caches in WebView: web page data cache (storing opened pages and resources), and H5 cache (ie AppCache).

Save the web page url and web page files (css, pictures, js, etc.) we have browsed to the database table

 

Cache mode (5 kinds)
LOAD_CACHE_ONLY: Do not use the network, only read the local cache data
LOAD_DEFAULT: Determine whether to fetch data from the network according to cache-control.
LOAD_CACHE_NORMAL: It has been deprecated in API level 17. It has the same effect as LOAD_DEFAULT mode since API level 11.
LOAD_NO_CACHE: does not use cache, only obtains data from the network.
LOAD_CACHE_ELSE_NETWORK, as long as it is available locally, whether it expires or no-cache, use the cached data data.


For example, the cache-control of www.taobao.com is no-cache. In the mode LOAD_DEFAULT, the data will be retrieved from the network anyway. If there is no network, an error page will appear; in the LOAD_CACHE_ELSE_NETWORK mode, regardless of whether there is a network, As long as there is a local cache, the cache is used. It is obtained from the network when there is no local cache.
The cache-control of www.360.com.cn is max-age=60, and local cache data is used in both modes.

Summary: According to the above two modes, the recommended caching strategy is to determine whether there is a network, and if so, use LOAD_DEFAULT, and when there is no network, use LOAD_CACHE_ELSE_NETWORK.

 

Effect picture:

        

According to the Baidu homepage to test, load when there is a network, then close the network and end the process, and you can see the previously seen web page when you open it. When you click on a page that has not been opened, it is:

       

The cached data directory is by default under: data/data/package name/app_webview/Cache/:

Code:

 

public class MainActivity extends Activity {

    private WebView webView;
    private String url = "https://wap.baidu.com/";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    public void initView() {
        webView = (WebView) findViewById(R.id.activity_webview);
        webView.requestFocus();
        webView.setHorizontalScrollBarEnabled(false);
        webView.setVerticalScrollBarEnabled(false);
        initWebView();

    }

    @SuppressWarnings("deprecation")
    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {

        webView.getSettings().setJavaScriptEnabled(true);
        // set cache mode
        if (NetUtils.isNetworkAvailable(MainActivity.this)) {
            webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        } else {
            webView.getSettings().setCacheMode(
                    WebSettings.LOAD_CACHE_ELSE_NETWORK);
        }
        // webView.getSettings().setBlockNetworkImage(true);// Put the image loading at the end to load and render
        webView.getSettings().setRenderPriority(RenderPriority.HIGH);
        // support multiple windows
        webView.getSettings().setSupportMultipleWindows(true);
        // Enable DOM storage API function
        webView.getSettings().setDomStorageEnabled(true);
        // Enable Application Caches function
        webView.getSettings().setAppCacheEnabled(true);
        onLoad();
    }

    @SuppressWarnings("deprecation")
    @SuppressLint("SetJavaScriptEnabled")
    public void onLoad() {

        try {
            webView.setWebViewClient(new WebViewClient() {

                @Override
                public void onLoadResource(WebView view, String url) {

                    Log.i("tag", "onLoadResource url=" + url); // start loading
                    super.onLoadResource(view, url);
                }

                @Override
                public boolean shouldOverrideUrlLoading(WebView webview,
                        String url) {

                    Log.i("tag", "intercept url=" + url);
                    // Rewrite this method to indicate that clicking on the link in the web page still jumps in the current webview, not the browser
                    webview.loadUrl(url);

                    return true;
                }

                @Override
                public void onPageFinished(WebView view, String url) {

                    String title = view.getTitle(); // get the page title

                    Log.e("tag", "onPageFinished WebView title=" + title);

                }

                @Override
                public void onReceivedError(WebView view, int errorCode,
                        String description, String failingUrl) {

                    Toast.makeText(getApplicationContext(), "Load Error",
                            Toast.LENGTH_LONG).show();
                }
            });
            webView.loadUrl(url);
        } catch (Exception e) {
            return;
        }
    }

    @Override
    // set fallback
    // Override the onKeyDown(int keyCoder,KeyEvent event) method of the Activity class
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
            webView.goBack(); // goBack() means to return to the previous page of WebView
            return true;
        } else {
            finish();
        }
    }

    /***
     * Prevent WebView loading memory leak
     */
    @Override
    protected void onDestroy() {
        super.onDestroy ();
        webView.removeAllViews();
        webView.destroy();
    }

}

 

Add permissions to AndroidManifest.xml

 

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

 

The code is not fully given, you can download the source code directly

 

Source code click to download

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326266102&siteId=291194637