Basic Android tutorial -- 7.5.5 WebView cache problem, 7.5.5webview
Basic Android tutorial -- 7.5.5 WebView cache Problems
Tags (separated by spaces): basic Android tutorial
This section introduces:
Currently, many portal information websites, such as Tiger sniffing, ifanr, and titanium media, are simply information reading apps.
A WebView is directly nested to display relevant information, which may involve the cache of WebView! The so-called page Cache
This means to save the HTML, JS, CSS, and other page-related data and other resources required for loading a webpage.
When the network status is poor, load the locally saved data! There are two ways to implement this cache: one is to write one in the background
Download the Service, download the article-related data to the database or save it to the corresponding folder as needed, and then load it next time
Determine whether the local cache exists before the corresponding URL. If the local cache is preferentially loaded, the online request is executed if the local cache does not exist.
Related resources, such as the 36Kr of the old version, are displayed after going in! Of course, this section does not explain
This method uses the cache function provided by WebView to cache pages.
Simple: you only need to enable the relevant functions for WebView settings and set the cache path for the database to complete the cache! Specific
The following is an example of implementation ~
1. cache classification:
The first thing we need to talk about is the cache classification. The cached data is divided:Page cache and data cache
Page Cache: When loading a webpage, html, JS, CSS, and other page or resource data, these cache resources are caused by the browser
Developers can only indirectly affect the cached data by configuring HTTP response headers.
WhileCache IndexPut in:/data/<package name>/databases
Corresponding FilePut in:/data/package_name/cache/webviewCacheChromunm
Data Cache: AppCache and DOM Storage
What we developers can control on their own is the cache resources,
- AppCache: We can choose to buffer everything in the web browser, from pages, images to scripts, css, and so on.
It is especially useful when it comes to CSS and JavaScript files applied to multiple pages of a website. The current size is usually 5 MB.
You need to manually enable setAppCacheEnabled on Android and set the path (setAppCachePath) and capacity
(SetAppCacheMaxSize), which is used in AndroidApplicationCache. dbTo save AppCache data!
- DOM Storage: Stores some simple data that can be solved by using key/value pairs. sessions are available based on different scopes.
Storage and Local Storage are used for session-level Storage (when the page is closed, it disappears) and Local Storage (unless the active
Delete, otherwise the data will never expire.) In Android, You can manually enable DOM Storage (setDomStorageEnabled ),
Webkit in Android sets the storage path (setDatabasePath) generates 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 lying in a slot, what the hell is it? It looks so complicated?
Of course, don't back it up. You just need to know about these things. You can use them in actual development, And we generally only care about how
Set cache for WebView and how to delete cache!
Let's take a look at the File structure after the demo is run, and open the File Explorer of DDMS:
Hey, you can see it at a glance ~, By the way, we also need to talk about several cache modes:
- LOAD_CACHE_ONLY: Read Only local cache data without using the network
- LOAD_DEFAULT: Determines whether to retrieve data from the Network Based on cache-control.
- LOAD_CACHE_NORMAL: API level 17 has been deprecated. The function of API level 11 is the same as that of LOAD_DEFAULT.
- LOAD_NO_CACHE: No cache is used. Only data is obtained from the network.
- LOAD_CACHE_ELSE_NETWORKThe cached data is used as long as it exists locally, no matter whether it expires or not.
Summary: Based on the above two modes, we recommend that you use the cache policy to determine whether a network exists. If yes, use LOAD_DEFAULT,
When no network exists, use LOAD_CACHE_ELSE_NETWORK.
Next, the stacking time!
2. Enable the cache function for WebView
The following describes how to enable the cache function for WebView:
Run:
Process Analysis:
1. After Entering the page, the url is loaded by default. Click a link to jump to the second page and exit the APP.
2. Disable wifi and the mobile network, and then enter again. When no network is found, the page is still loaded,
Opening the first link can also be loaded. Opening other links will find that the webpage cannot be found!
3. Click "Clear cache", close the application, and enter again. The page cannot be opened!
The following is 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 webpage opened when you click in webView to be displayed on the current page without redirecting to the new browser @ Override public boolean shouldOverrideUrlLoading (WebView view, string url) {view. loadUrl (url); return true ;}}); WebSettings settings = wView. getSettings (); settings. setJavaScriptEnabled (true); // sets the cache Mode settings. setCacheMode (WebSettings. LOAD_CACHE_ELSE_NETWORK); // enable the DOM storage API function settings. setDomStorageEnabled (true); // enable the database storage API function settings. setDatabaseEnabled (true); String cacheDirPath = getFilesDir (). getAbsolutePath () + APP_CACHE_DIRNAME; Log. I ("cachePath", cacheDirPath); // sets the 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. revoke AchE (true) ;}}); btn_refresh.setOnClickListener (new View. onClickListener () {@ Override public void onClick (View v) {wView. reload () ;}}) ;}// click the event @ Override public void onBackPressed () {if (wView. canGoBack () {wView. goBack ();} else {super. onBackPressed ();}}}
The code is simple. What we do is to enable the cache function and set the cache mode and cache data path!
3. Delete cache data of WebView
In the preceding example, we have deleted the cache by calling the WebView revoke AchE (true) method!
In addition to this method, there are also the following methods:
- Setting. setCacheMode (WebSettings. LOAD_NO_CACHE);
- DeleteDatabase ("WebView. db"); and deleteDatabase ("WebViewCache. db ");
- WebView. clearHistory ();
- WebView. clearFormData ();
- GetCacheDir (). delete ();
- Manually write the delete method and delete the cache folder cyclically!
Of course, as mentioned above, we can directly operate on only the data part, and the page cache is caused by the browser
The HTTP response header can be configured to indirectly affect browser behavior.
The cached data. Therefore, the preceding method only caches the deleted data!
4. Download the sample code:
WebViewDemo7.zip: Ttp: // pan.baidu.com/s/1dDi6WMH
5. Summary in this section:
Okay, this section is about WebView caching. Here we only write how to enable caching for WebView,
And the deletion of the cache. I will try again later. Here is an image first ~ Well, that's all ~ Thank you.
By the way, I almost forgot to paste the reference link for this section:
Android webView Cache + HTML5 offline Function Solution
Android recording 25-WebView for offline cache reading
Android clears WebView Cache
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.