The use of WebView

Source: Internet
Author: User
Tags delete cache

Basic usage

Layout file Configuration WebView

          <webview            android:id= "@+id/wv_news_detail"            android:layout_width= "match_parent"            android:layout_ height= "Match_parent"/>

WebView Loading Web pages

Load Web link        mwebview.loadurl ("http://www.itheima.com");        Load the Web page        mwebview.loadurl ("file:///android_asset/demo.html") under the local assets directory;

WebView Basic Settings

        WebSettings settings = Mwebview.getsettings ();        Settings.setbuiltinzoomcontrols (TRUE);//Display Zoom button (WAP page not supported)        Settings.setusewideviewport (TRUE);//Support double-click Zoom ( WAP Page not supported)        settings.setjavascriptenabled (TRUE);//Support JS function

Set Webviewclient

  Mwebview.setwebviewclient (New Webviewclient () {//Start loading Web page @Override public void Onpages                tarted (WebView view, String URL, Bitmap favicon) {super.onpagestarted (view, URL, favicon);            System.out.println ("Start loading Web page");                }//page load ends @Override public void onpagefinished (WebView view, String URL) {                super.onpagefinished (view, URL);            System.out.println ("End of page loading"); }//All links jump Move This method @Override public boolean shouldoverrideurlloading (WebView view, String u                RL) {System.out.println ("Jump link:" + URL); View.loadurl (URL);//force loading in the current WebView when jumping links//This method also has other scenarios, such as writing a hyperlink <a href= "tel:110" > Contact us </a> When you click the hyperlink, you can get the link address tel:110 in this method,//Resolve the address, get the phone number, and then jump to the local call page instead of loading the Web page, enabling webview and local code interaction RET            Urn true; }        });

Set Webchromeclient

Mwebview.setwebchromeclient (New Webchromeclient () {            @Override public            void onprogresschanged (WebView view, int newprogress) {                super.onprogresschanged (view, newprogress);                Progress changed                System.out.println ("Progress:" + newprogress);            }            @Override public            void Onreceivedtitle (WebView view, String title) {                super.onreceivedtitle (view, title);                Page title                System.out.println ("page title:" + title);            }        );

WebView loading previous page and next page

Mwebview.goback ();//Jump to the previous page Mwebview.goforward ();//Jump to the next page mwebview.cangoback ();//Whether you can skip to the previous page (if you return false, the first page is already) Mwebview.cangoforward ();//Whether you can skip to the next page (if it returns false, it is already the last page)

WebView Advanced Usage

Cache Settings

WebSettings settings = Mwebview.getsettings ();        The Data        Settings.setcachemode (websettings.load_cache_else_network) in the cache is used as long as the local has, whether or not expired, or no-cache;        Load only cache        Settings.setcachemode (websettings.load_cache_only);        Decide whether to fetch data        Settings.setcachemode (Websettings.load_default) from the network according to Cache-control;        Do not load cache        Settings.setcachemode (websettings.load_no_cache);    

What is Cache-control?

Cache-control is the response header of the server when the page is requested, which is used to determine the caching policy for the Web page.

Common values are public (all content will be cached), private (content is cached only in the private cache), No-cache (all content is not cached), max-age=xxx (cached content will expire after xxx seconds), etc.

:




Clean up the cache

   Easiest way:        Mwebview.clearcache (true);        Another way:        //Delete cache folder        File File = Cachemanager.getcachefilebasedir ();            if (file = null && file.exists () && file.isdirectory ()) {for             (file Item:file.listFiles ()) {              it Em.delete ();             }             File.delete ();            }         Delete Cache database        context.deletedatabase ("webview.db");         Context.deletedatabase ("webviewcache.db");

Cookie settings

        Cookiesyncmanager.createinstance (this);        Cookiemanager Cookiemanager = Cookiemanager.getinstance ();        Cookiemanager.setacceptcookie (true);        String cookie = "name=xxx;age=18";        Cookiemanager.setcookie (URL, cookie);        Cookiesyncmanager.getinstance (). sync ();

Get cookies

        Cookiemanager Cookiemanager = Cookiemanager.getinstance ();        String cookie = Cookiemanager.getcookie (URL);

Clearing cookies

        Cookiesyncmanager.createinstance (context);          Cookiemanager Cookiemanager = Cookiemanager.getinstance ();         Cookiemanager.removeallcookie ();        Cookiesyncmanager.getinstance (). sync ();

Demo Demos:

Package Com.loaderman.webviewdemo;import Android.graphics.bitmap;import Android.os.bundle;import Android.support.v7.app.appcompatactivity;import Android.webkit.webchromeclient;import android.webkit.WebSettings ; Import Android.webkit.webview;import Android.webkit.webviewclient;public class Mainactivity extends appcompatactivity {@Override protected void onCreate (Bundle savedinstancestate) {super.oncreate (Savedinstan        Cestate);        Setcontentview (R.layout.activity_main);        WebView Mwebview = (WebView) Findviewbyid (r.id.wv_test);        Load Web link mwebview.loadurl ("http://www.baidu.com");        Load the Web page//mwebview.loadurl ("file:///android_asset/demo.html") under the local assets directory;        WebSettings settings = Mwebview.getsettings ();        Settings.setbuiltinzoomcontrols (TRUE);//Display Zoom button (WAP page not supported) Settings.setusewideviewport (TRUE);//Support double-click Zoom (WAP page not supported)   Settings.setjavascriptenabled (TRUE);//Support JS function mwebview.setwebchromeclient (new Webchromeclient () {         @Override public void onprogresschanged (WebView view, int newprogress) {Super.onprogre                Sschanged (view, newprogress);            Progress changed SYSTEM.OUT.PRINTLN ("Progress:" + newprogress); } @Override public void Onreceivedtitle (WebView view, String title) {super.onreceive                Dtitle (view, title);            Page title System.out.println ("page title:" + title);        }        }); Mwebview.setwebviewclient (New Webviewclient () {//Start loading Web page @Override public void Onpagesta                RTed (WebView view, String URL, Bitmap favicon) {super.onpagestarted (view, URL, favicon);            System.out.println ("Start loading Web page");                }//page load ends @Override public void onpagefinished (WebView view, String URL) {                super.onpagefinished (view, URL);            System.out.println ("End of page loading");        }    All links jump Move This method @Override public boolean shouldoverrideurlloading (WebView view, String URL) {                System.out.println ("Jump link:" + URL); View.loadurl (URL);//force loading in the current WebView when jumping links//This method also has other scenarios, such as writing a hyperlink <a href= "tel:110" > Contact us </a> When you click the hyperlink, you can get the link address tel:110 in this method,//Resolve the address, get the phone number, and then jump to the local call page instead of loading the page, enabling WebView and local code to interact with return T            Rue    }        }); }}

Activity_main.xml

<?xml version= "1.0" encoding= "Utf-8"? ><relativelayout    xmlns:android= "http://schemas.android.com/apk /res/android "    xmlns:tools=" Http://schemas.android.com/tools "    android:id=" @+id/activity_main    " Android:layout_width= "Match_parent"    android:layout_height= "match_parent"    tools:context= " Com.loaderman.webviewdemo.MainActivity ">    <webview        android:id=" @+id/wv_test "        android:layout_ Width= "Match_parent"        android:layout_height= "Match_parent"/></relativelayout>

To add Network permissions:

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

:

Run directly open the page Baidu first page

Read the log directly:

WebView's application Scenario

WebView application Scenarios We don't need to talk more, here I only mention: with the popularity of HTML5, many apps will be embedded webview to load HTML5 pages, and H5 do with the app native controls are very similar, So how do we identify a page using H5 or native controls?
Open developer options and you'll see an option to show layout boundaries

When checked, the borders of all native control layouts will be displayed.

We are now in this state to open a webview to take a look (this is the wallet-drip travel page)

If it is webview, only on the edge of WebView will display a border, webview interior is no border, if it is a native control, how can the border so little? Thus we can conclude that the Drip travel page must be implemented with WebView loading Web pages, rather than the system native controls.

The use of WebView

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.