One 、 Basic introduction

WebView It's a component that displays pages .

Two 、 Basic use

Access to the web requires the web , So in AndroidManifest.xml Add network permissions to the file .

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

have access to Intent The jump page , Use as follows :

Uri uri = Uri.parse("http://www.baidu.com");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);

Use Intent The jump page , Will call the local browser to view the web page information .

stay onCreate() method contentView Set to webView, The method is as follows :

WebView webView = new WebView(this);
setContentView(webView);
loadUrl("http://www.baidu.com");

This method , The whole interface is web content .

There is also a way to webView As a component of the whole interface , stay activity_main Add WebView Components , as follows :

 <WebView
android:id="@+id/web_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />

stay MainActivity.java Use in WebView, The code is as follows :

webView = (WebView) findViewById(R.id.web_view);
webView.loadUrl("http://www.baidu.com");

3、 ... and 、 Setting up support JavaScript

If you use JavaScript, Do not set support JavaScript Words , The web page doesn't display properly , If you use JavaScript, Need to set up support JavaScript.

// Launch support javascript
webView.getSettings().setJavaScriptEnabled(true);

Four 、 When you click the back button, the page you want to browse will go back instead of leaving the browser

When you want to click the back button, the page you are browsing will go back one page , Instead of just exiting the browser , It needs to be rewritten onKeyDown function , call WebView Of geBack() Method back and forth one page .

 // Rewrite the logic of the return key 
// I hope to click the back button, and web page back is not to exit the browser
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (webView.canGoBack()) {
webView.goBack();// Go back to the previous page
return true;
} else {
System.exit(0);// Exit procedure
}
}
return super.onKeyDown(keyCode, event);
}

5、 ... and 、 Judge the page loading process

Set up WebView Of WebChromeClient() Method to determine the loading of the page . As a browser UI When there is a change , such as , Progress updates and JavaScript Alerts are sent to WebChromeClient Class . It can also intercept URL Load in this ( Use shouldoverrideurlloading() Method ).

 // Web loading process 
webView.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int newProgress) {
Toast.makeText(MainActivity.this, "newProgress = " + newProgress, Toast.LENGTH_SHORT).show();
if (newProgress == 100) {
// Page loaded successfully
//Toast.makeText(MainActivity.this," Page loaded successfully ",Toast.LENGTH_SHORT).show();
} else {
//Toast.makeText(MainActivity.this," Page loading failed ",Toast.LENGTH_SHORT).show();
}
}
});

But when it comes in ,newProgress be equal to 10 When , The page has been shown , Use this method to determine the loading situation , I don't feel very reliable .

6、 ... and 、 Page caching

WebView There are two types of caching for :

The first one is : Browser's own web data cache .

Browser caching mechanism is through HTTP agreement Header Inside Cache-Control( or Expires) and Last-Modified( or Etag) To control the file caching mechanism .

When receiving a response , according to Cache-Control( or Expires) The browser decides whether the file needs to be cached , Or when you need to load a file , The browser decides whether the requested field is needed .

When making a request , according to Last-Modified( or Etag) Fields that the server decides whether the file needs to be updated .

By setting WebView Of Cache Mode, So as to make the agreement effective or invalid .

WebView Of Cache Mode:

LOAD_CACHE_ONLY: Don't use the Internet , Read only the local cache data .

LOAD_DEFAULT: according to cache-control Decide whether to retrieve data from the network .

LOAD_CACHE_NORMAL:API level 17 Has been abandoned , from API level 11 It works the same as LOAD_DEFAULT Pattern .

 LOAD_NO_CACHE: Do not use cache , Only get data from the network .

 LOAD_CACHE_ELSE_NETWORK, As long as there is , Whether or not it expires , perhaps no-cache, All use the data in the cache . Get from the network when there is no cache locally .

WebView Cache usage

// Set up webView The cache mode of is : according to cache-control Decide whether to retrieve data from the network 
webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);

The second kind :H5 The cache of

Write Web The page code is , Appoint manifest Property to make the page use App Cache.

AppCache How it works : When one is set manifest Of documents html When the page is loaded ,CACHE MANIFEST The specified file will be cached in the browser App Cache Below directory . The next time you load this page , Will pass first manifest Files that have been cached , Then initiate a load xxx.appcache File request to the server , If xxx.appcache The document has not been modified , Then the server will return 304 Not Modified To the browser , If xxx.appcache The file has been modified , Then the server will return 200 OK, And return a new xxx.appcache The contents of the file are sent to the browser , When the browser receives it , And put the new xxx.appcache The contents specified in the file are loaded and cached .

WebView Support AppCache:

 // Support AppCache
WebSettings webSettings = webView.getSettings();
webSettings.setAppCacheEnabled(true);
String cachePath = getApplicationContext().getCacheDir().getPath();
webSettings.setAppCachePath(cachePath);

The difference between the two methods :

The same thing

WebView Built in cache and AppCache They can be used for file level caching , Basically, it is better to meet the requirements for non covering js、css Wait for the file to update .

Difference

WebView The built-in cache is implemented by the protocol layer ( Browser kernel standard implementation , Developers can't change ); and AppCache It's implemented in the application layer .

WebView The cache directory may be different on different systems ; And for AppCache for ,AppCache Although there is a way to set the storage path of , But they are all stored in a fixed internal private directory .

WebView The built-in cache does not need to be sent again when the cache takes effect HTTP request ; and AppCache There must be a manifest File request .

WebView The built-in cache can be set by CacheMode To change WebView Cache mechanism ; and AppCache The cache policy of is made up of manifest Document controlled , That is to say, by web Page developer controlled .

A lot of times , These two types of caching work together , When manifest When the file does not control the loading of some resources , These resources will come to WebView The built-in cache mechanism to , combination WebView Of CacheMode.

Full code address :https://github.com/ZhangMiao147/WebViewCacheDemo

Reference article :http://cs.szpt.edu.cn/android/reference/android/webkit/WebView.html

       http://unclechen.github.io/2017/05/13/WebView%E7%BC%93%E5%AD%98%E5%8E%9F%E7%90%86%E5%88%86%E6%9E%90%E5%92%8C%E5%BA%94%E7%94%A8/

WebView More related articles on knowledge of

  1. webview Related knowledge

    The tag class 1.Web App Suggested style Used to cover WebView Default style , bring App It looks more like native App,——“ Don't show your horse's feet ” /* document.documentElement.st ...

  2. WebView The use of, ( One )——Native And JS Mutual invocation ( attach JadX Decompile )

    Not forget for a moment , There must be an echo , Always stick to what you stick to ! Have been using WebView, There is no systematic summary of its use , Here is a summary of the system , Share with you One . Basic usage 1. Load Online URL void loadUrl(String ...

  3. Anaroid WebView Complete explanation

    Resource description : 1.android Provides webView Control is designed to browse web pages . And then load it in the program webView Control , Set properties , such as : Color . typeface . Website to visit, etc . adopt loadUrl Method to set the current webView need ...

  4. Anaroid WebView API Detailed explanation

    android Provides webView Control is designed to browse web pages Use WebView when , Load... In the program WebView Control , You can put WebView In the layout , It can also be dynamic New Out WebView example , You can set properties , such as : ...

  5. Android be based on JsBridge Encapsulation efficiency with loading schedule WebView

    Tamic http://blog.csdn.net/sk719887916/article/details/52402470 summary From last year 4 Monthly projects have been used JsBridge, The front also aims at jsBrid ...

  6. Android SDK Components :webview note

    1. Android phones have a built-in webkit Browser for kernel , stay SDK It is encapsulated as WebView Components . 2. This component can display local or Internet Web page on , You can also use it as a browser . 3.We ...

  7. 【Web technology 】 275- understand WebView

    Preface understand webview The mystery of . Read the article this morning by @ Sub non translation sharing . The text starts here -- We usually use Chrome, Firefox, Safari, Internet Explorer and Edge ...

  8. mui Introductory course ( Two )— html5+ webview Usage of bottom column

    Source of the article : Young people's original release time :2016-05-19 key word :mui,html5+,webview Reprint should be marked with the original address of this article : http://zhaomenghuan.github.io/#!/blog/20 ...

  9. WebView The use of, ( Two )——WebViewClient With common event monitoring

      Sign in | register     close Start a ship When a turtle has a dream ……       Catalog view Summary view subscribe Asynchronous book donation :Kotlin Leading 10 A good book        Free live broadcast :AI Time , Machines learn how to get started ?       The programmer 8 ...

Random recommendation

  1. About ExtJS、JQuery UI and easy UI The choice of

    I know from Baidu . ask : Do enterprise applications , such as *** Management system , You don't need fancy special effects , Just hope it's simple , Uniform style . All you can use is messagebox.tree.grid About these , Other special effects don't , Forget God according to my own opinion and my ...

  2. Postman test Web API

    How to view query strings ? → Enter... Containing the query string URL, such as :http://localhost:54176/api/ProductCategories?name=darren&age=25→ Click on P ...

  3. How to debug Typescript in browser

    How to debug typescript, In Chrome, we need to press F12, open settings, uncheck the Enable JavaScri ...

  4. A Personal Selection of Books on E lectromagnetics and Computational E lectromagnetics---David B. Davidson

    link . General Books on Electromagnetics When our department recently reviewed our junior-level text, w ...

  5. &amp;&amp; and || That little thing about

    I used to think && and || The result of this operation is a Boolean value , But today I see some knowledge loopholes filled by a piece of code . var a = (1&&2&&5) || 3; console.l ...

  6. Golang Of iota Characteristics of

    Golang Of iota Characteristics of : 1. iota At every ConstBlock Automatically return to 0. 2. iota At every ConstSpec After the automatic increase 1. In other words : iota yes ConstBlock in ConstSpec Of ...

  7. Generate package.json and bower.json

    1. install nodejs 2. install bower Tools   cmd:npm bower install 3. Generate package.json  cmd:npm init 4. Generate bower.json cmd:bow ...

  8. Unrecognized property “targetFramework”

    Problem description : Unrecognized property “targetFramework”. Note that property names are case sensitive . terms of settlement : modify .NET Framework The version is the corresponding version , for example 2.0 Switch to 4.0. Reference resources :http://bl ...

  9. The probability method is used to solve the third order magic square [C Language ]

    #include <stdio.h> #include <string.h> ]={,,,,,,,,}; ]; ][]; int sum(int su[]) { ; ;su[i ...

  10. DELETE_FAILED_INTERNAL_ERROR Error while Installing APK

    It's Android2.3 The special version problem of , The reason for the problem is android2.3 Of instant run There is a special way to install the beta version of , The solution is 2: 1. Manual adb install Installation package 2. hold Instant r ...