Android Basics Getting Started tutorial--7.5.5 WebView caching issues

Source: Internet
Author: User

Android Basics Getting Started tutorial--7.5.5 WebView caching issues

tags (space delimited): Android Basics Getting Started Tutorial

Introduction to this section:

Now a lot of portal information sites, such as Tiger sniffing, IFANR, titanium media and so on the app, simple point is the information reading app, a lot of
are nested directly in a webview to display relevant information, which may involve the WebView cache! The so-called page cache
means to save the data and other resources that are needed to load a Web page, such as HTML,JS,CSS, when there is no net or
When the network status is poor, load the locally saved relevant data! There are two ways to implement this cache, one is to write a background
Download the service, download the article related data to the database according to your own requirements, or save it to the appropriate folder, and then load it next time
To determine if there is a local cache before the URL, if there is a priority to load the local cache, does not exist to perform networking requests, while caching
Related resources, typical of the same version of the 36Kr, after entering the offline article, and then display! Of course, this sectionto is not explaining
This way of writing logic, instead of caching the page by WebView itself with its own caching function, this method is used very
Simple, we only need to set the relevant function for WebView, and set the database cache path to complete the cache! Specific to
To achieve the following one by one of our way ~

1. Classification of the cache:

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

  • page cache : HTML, JS, CSS, and other pages or resource data when a Web page is loaded, which is generated by the behavior of the browser
    . Developers can only configure HTTP response headers to affect the browser's behavior to indirectly affect these cached data.
    The cached index is placed in the:/data/data/< package name >/databases
    The corresponding file is placed in:/data/data/package_ NAME/CACHE/WEBVIEWCACHECHROMUNM under

  • data cache : Divided into AppCache and Dom storage two kinds
    The cache resources that our developers can control themselves,

    • AppCache: We have the option to buffer everything from Web browsers, from pages, images to scripts, CSS, and so on.
      This is especially useful when it comes to CSS and JavaScript files that are applied to multiple pages on a Web site. Its size is now usually 5M.
      On Android requires manual on (setappcacheenabled), and set the path (Setappcachepath) and capacity
      (Setappcachemaxsize), while Android uses applicationcache.db to save AppCache data!
    • DOM Storage: Store Some simple data that can be solved with key/value, depending on the range of functions, there is a session
      Storage and local storage two, respectively, for session-level storage (page close disappears) and localized storage (unless active
      deleted, otherwise the data will never expire) in Android you can manually turn on Dom Storage (setdomstorageenabled),
      Setting the storage path (SetDatabasePath) in Android WebKit will generate two files for Domstorage (my_path/localstorage/http_blog.csdn.net_0. Localstorage and My_path/databases.db)

Well, after reading the above, is not want to say, lying trough, what ghost, good complex look
Of course, do not go to the back, know that there are these things good, the actual development of the use of more slowly refined, and we generally only care about how to
Set the cache for WebView and how to delete it!
We can look at the post-run file structure we wrote below, and open the files Explorer for DDMS:

Hey, at a glance is it ~, on the other also have to say several cache mode:

  • load_cache_only: Do not use the network, only read local cache data
  • Load_default: Decide whether to fetch data from the network according to Cache-control.
  • load_cache_normal: Deprecated in API level 17, starting from API level 11 with Load_default mode
  • Load_no_cache: Do not use caching, only get data from the network.
  • load_cache_else_network, the data in the cache is used whenever there is a local, regardless of whether it expires, or No-cache.

Summary : According to the above two models, the proposed cache strategy for, to determine whether there is a network, if so, using Load_default,
When there is no network, use Load_cache_else_network.

Next heap the code time!

2. Turn on the cache function for WebView

Let's turn on caching for WebView, and take a look at the implementation:

Run :

Process Analysis :
1. After entering the page, load the URL by default, then click on a link to skip to the second page and exit the app.
2. Close WiFi and mobile network, and then re-enter, found no network, the page is still loaded,
Open the first link can also be loaded, open the other links to find the page cannot be found!
3. Click Clear Cache, close the app, re-enter, find the page has not opened!

Next is the code implementation:Mainactivity.java:

 Public  class mainactivity extends appcompatactivity {    PrivateWebView Wview;PrivateButton Btn_clear_cache;PrivateButton Btn_refresh;Private Static FinalString App_cache_dirname ="/webcache";//Web cache directory    Private Static FinalString 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 (NewWebviewclient () {//Set in WebView Click to open the new page displayed in the current screen without jumping to the new browser            @Override             Public Boolean shouldoverrideurlloading(WebView view, String URL) {view.loadurl (URL);return true;        }        });        WebSettings settings = Wview.getsettings (); Settings.setjavascriptenabled (true);//Set Cache modeSettings.setcachemode (websettings.load_cache_else_network);//Open DOM storage API functionSettings.setdomstorageenabled (true);//Open database Storage API functionSettings.setdatabaseenabled (true);        String Cachedirpath = Getfilesdir (). GetAbsolutePath () + app_cache_dirname; LOG.I ("CachePath", Cachedirpath);//Set Database cache pathSettings.setappcachepath (Cachedirpath); Settings.setappcacheenabled (true); LOG.I ("DatabasePath", Settings.getdatabasepath ()); Btn_clear_cache.setonclicklistener (NewView.onclicklistener () {@Override             Public void OnClick(View v) {Wview.clearcache (true);        }        }); Btn_refresh.setonclicklistener (NewView.onclicklistener () {@Override             Public void OnClick(View v)            {wview.reload ();    }        }); }//Override click event for fallback button    @Override     Public void onbackpressed() {if(Wview.cangoback ())        {Wview.goback (); }Else{Super. onbackpressed (); }    }}

The code is simple, and all we do is turn on the cache and set the cache mode and the path to the cached data!

3. Delete WebView Cache data

For the above example, we have implemented the deletion of the cache by calling WebView's ClearCache (true) Method!
In addition to this approach, there are the following methods:

  • Setting.setcachemode (Websettings.load_no_cache);
  • DeleteDatabase ("Webview.db"), and DeleteDatabase ("webviewcache.db");
  • webview.clearhistory ();
  • webview.clearformdata ();
  • getcachedir (). Delete ();
  • Write the Delete method manually and iterate to delete the cache folder!

Of course, the front also says that we can only manipulate the data part directly, and the page cache is due to the browser
Behavior, we can only influence the browser's behavior by configuring the HTTP response header to indirectly affect
These cached data. So the above method is just to delete the data part of the cache!

4. Sample code Download:

webviewdemo7.zip: TTP://PAN.BAIDU.COM/S/1DDI6WMH

5. Summary of this section:

OK, this section about WebView cache problem is here, here just wrote how to open the cache for WebView,
and delete the cache, later encountered again slowly refined, here is an image first ~ Well, say so much ~ Thank you

Yes, I almost forgot to post the reference link to this section:
Android WebView Caching cache + HTML5 offline function resolution
Android record 25-webview for offline cache reading
Android Clear WebView Cache

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android Basics Getting Started tutorial--7.5.5 WebView caching issues

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.