Android WebView caching problem

17096416:

Introduction to this section:

Nowadays, many portal information websites, such as Huxiu, ifanr, Titanium Media and other APPs, are simply information reading APPs. Many of them directly nest a WebView to display relevant information. This may be involved. WebView is cached!

The so-called page cache refers to: saving the HTML, JS, CSS and other page-related data and other resources required when loading a web page. When there is no network or the network status is poor, load the locally saved relevant data! There are two ways to implement this cache. One is to write a download service in the background, download the article-related data to the database or save it to the corresponding folder according to your own needs, and then determine whether the corresponding URL is loaded next time. There is a local cache. If it exists, the local cache will be loaded first. If it does not exist, the network request will be executed and related resources will be cached. A typical example is the old version of 36Kr. After entering, the article will be offline first and then displayed!

Of course, what this section is going to explain is not this way of writing your own logic, but caching the page through the caching function that comes with WebView itself. This method is very simple to use. We only need to enable relevant functions for WebView settings, and set The cache path of the database can be used to complete the cache! Let’s go through the specific implementation one by one~


1. Categories of cache:

The first thing to say is the classification of cache. The data we cache is divided into: page cache and data cache.

  • Page cache : HTML, JS, CSS and other page or resource data when loading a web page. These cached resources are generated due to the behavior of the browser. Developers can only affect the behavior of the browser indirectly by configuring HTTP response headers. These cache data. The cached index is placed under:/data/data/<package name>/databases  and the corresponding file is placed under:/data/data/package_name/cache/webviewCacheChromunm

  • Data cache : It is divided into two types: AppCache and DOM Storage. These cache resources are what our developers can control by themselves.

  • AppCache : We can selectively cache everything in the web browser, from pages and images to scripts, css, etc. This is especially useful when it comes to CSS and JavaScript files that are applied to multiple pages of the website. Its size is currently usually 5M. On Android, you need to manually turn on (setAppCacheEnabled) and set the path (setAppCachePath) and capacity (setAppCacheMaxSize). ApplicationCache.db is used in Android to save AppCache data!

  • DOM Storage : Stores some simple data that can be solved using key/value pairs. Depending on the scope of the application, there are two types: Session Storage and Local Storage, which are used for session-level storage (the page disappears when it is closed) and localized storage respectively. (Data will never expire unless actively deleted) In Android, you can manually enable DOM Storage (setDomStorageEnabled) and set the storage path (setDatabasePath). Webkit in Android will generate two files for DOMStorage (my_path/localstorage/http_blog.csdn.net_0 .localstorage and my_path/Databases.db)

Okay, after reading the above, do you want to say something like, Damn, what the hell, it’s so complicated.

 Of course, don’t memorize it, it’s good to know that these things exist, and you will learn more about them later in actual development. And we generally only care about how to set the cache for WebView and how to delete the cache! We can take a look at the file structure after running the demo we wrote below, and open the File Explorer of DDMS:

Hehe, it’s clear at a glance, right? By the way, I’d also like to talk about several caching modes:

  • LOAD_CACHE_ONLY : Do not use the network, only read local cache data
  • LOAD_DEFAULT : Determine whether to retrieve data from the network based on cache-control.
  • LOAD_CACHE_NORMAL : Deprecated in API level 17, starting from API level 11, it works the same as LOAD_DEFAULT mode
  • LOAD_NO_CACHE : Do not use cache, only get data from the network.
  • LOAD_CACHE_ELSE_NETWORK , as long as it is available locally, regardless of whether it is expired or no-cache, the data in the cache will be used.

Summary : Based on the above two modes, the recommended caching strategy is to determine whether there is a network. If so, use LOAD_DEFAULT. When there is no network, use LOAD_CACHE_ELSE_NETWORK.

Next it’s stacking time!


2. Enable caching for WebView

Now let's enable the caching function for WebView. First, let's take a look at the implementation renderings:

Operation rendering :

Process analysis : 1. After entering the page, the url is loaded by default, then click on a link to jump to the second page, and exit the APP. 2. Turn off wifi and mobile network, and then re-enter. It is found that the page is still loaded even if there is no network. It can also be loaded when opening the first link, but when opening other links, I find that the web page cannot be found! 3. Click to clear cache, close the application, re-enter, and find that the page cannot be opened!

Next is the code implementation: MainActivity.java :

public class MainActivity extends AppCompatActivity {

    private WebView wView;
    private Button btn_clear_cache;
    private Button btn_refresh;
    private static final String APP_CACHE_DIRNAME = "/webcache"; // web cache directory
    private static final String URL = "http://blog.csdn.net/coder_pig";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        wView = (WebView) findViewById(R.id.wView);
        btn_clear_cache = (Button) findViewById(R.id.btn_clear_cache);
        btn_refresh = (Button) findViewById(R.id.btn_refresh);
        wView.loadUrl(URL);
        wView.setWebViewClient(new WebViewClient() {
            //Set the new web page opened by clicking on webView to be displayed in the current interface without jumping to a new browser
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
        WebSettings settings = wView.getSettings();
        settings.setJavaScriptEnabled(true);
        //Set cache mode
        settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        // Enable DOM storage API function
        settings.setDomStorageEnabled(true);
        // Enable database storage API function
        settings.setDatabaseEnabled(true);
        String cacheDirPath = getFilesDir().getAbsolutePath() + APP_CACHE_DIRNAME;
        Log.i("cachePath", cacheDirPath);
        //Set database cache path
        settings.setAppCachePath(cacheDirPath);
        settings.setAppCacheEnabled(true);
        Log.i("databasepath", settings.getDatabasePath());

        btn_clear_cache.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                wView.clearCache(true);
            }
        });

        btn_refresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                wView.reload();
            }
        });
    }

    //Rewrite the click event of the back button
    @Override
    public void onBackPressed() {
        if(wView.canGoBack()){
            wView.goBack();
        }else{
            super.onBackPressed();
        }
    }
}

The code is very simple. All we have to do is enable the cache function, set the cache mode and the path of the cached data!


3. Delete the cached data of WebView

In the above example, we have achieved deletion of the cache by calling the clearCache(true) method of WebView! In addition to this method, there are also the following methods:

  • setting.setCacheMode(WebSettings.LOAD_NO_CACHE);
  • deleteDatabase("WebView.db");和deleteDatabase("WebViewCache.db");
  • webView.clearHistory();
  • webView.clearFormData();
  • getCacheDir().delete();
  • Manually write the delete method and delete the cache folder iteratively!

Of course, as mentioned before, we can directly operate only the data part, and page caching is caused by the behavior of the browser. We can only indirectly affect these cached data by configuring HTTP response headers to affect the behavior of the browser. So the above method only deletes the cache of the data part!

Guess you like

Origin blog.csdn.net/leyang0910/article/details/131554081