Use of Android WebView (super detailed usage)

Time:2021-4-19

1.1 overview of WebView

Android WebView is a special view on the Android platform. It can be used to display web pages. This WebView class can be used to display only one online web page in the app. Of course, it can also be used to develop browsers.

The internal implementation of WebView uses WebKit to display the content of the view, and provides Web page forward and backward, web page zoom in, zoom out, search and other functions.

WebView is a control based on WebKit engine and displaying web pages. Android WebView adopts different WebKit kernel versions in low and high versions.

1.2 use of WebView

1.2.1 basic use of WebView

The simplest way to use WebView is to directly display the content of a web page. There are two steps:

  1. Add WebView control in layout file;
  2. Let the WebView control load and display the web page in the code.

Next, we will directly explain the case of using WebView control to display the content of Baidu home page

First, we add the WebView control to the layout file as follows:


Next, we need to make the WebView control load and display the web page in the code, as follows:

public class WebViewActivity extends AppCompatActivity {

Of course, here, we need to load the data content on the network, so we also need to add network permissions:


The running display is as follows:

image

1.2.2 WebView usage details

Generally speaking, WebView can be used alone or in combination with its subclasses

  1. Common methods of WebView;
  2. Common subclasses of WebView (websettings class, webviewclient class, webchromeclient class);
  3. Interaction between WebView and JavaScript.

1.2.2.1 common methods of WebView

  1. Status of WebView
//Activate WebView to be active, and the response of the web page can be executed normally
  1. Forward, backward page
//Can I go back

Common usage: back key control page back

Problem: when browsing a web page without any processing, click the “back” key of the system, and the whole browser using WebView will directly call finish() to end itself, close the current activity and return to the home screen (that is, directly exit the browser);

Well, here, we can do some processing. After clicking the “back” key, we can let the web page return to the previous page instead of exiting the browser directly.

At this point, we can process the back event in the current activity, as follows:

public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KEYCODE_BACK) && mWebView.canGoBack()) {
		mWebView.goBack();

		return true;

		}

		return super.onKeyDown(keyCode, event);

		}
  1. Clear cache
//Clear cache left by page access

1.2.2.2 common subclasses of WebView (websettings class, webviewclient class, webchromeclient class)

There are three common subclasses of WebView: websettings, webviewclient and webchromeclient.

  1. Websettings class

Function: configure and manage WebView;

Configuration steps;

Common methods.

Configuration steps:

Step 1: add network access rights( AndroidManifest.xml )


Step 2: generate a WebView component (in two ways)

//Method 1: generate directly in activity

Step 3: configure – use the websettings subclass (common method)

//Declare the websettings subclass

Common method: set WebView cache

//Cache priority
  1. Webviewclient class

Function: handle all kinds of notification & request events

Common methods

Common methods:

shouldOverrideUrlLoading()

Function: when opening a web page, it does not call the system browser to open it, but directly displays it in this WebView.

//WebView control

onPageStarted()

Function: call this method when loading the page. Here we can set a loading page to tell the user that the program is waiting for the network response.

webView.setWebViewClient (new WebViewClient(){

onPageFinished()

Function: called at the end of page loading. We can close the loading bar and switch the program action.

webView.setWebViewClient (new WebViewClient(){

onLoadResource()

Function: it will be called when loading page resources, and each resource (such as image) will be called once.

webView.setWebViewClient (new WebViewClient(){

onReceivedError()

Function: call when the server loading the page has an error (such as 404).

When using the WebView control in the app, we encounter errors such as 404. If we also display the error prompt page in the browser, it will be very ugly. At this time, our app needs to load a local error prompt page, that is, how does WebView load a local page

//Step 1: write an HTML file (error)_ handle.html ), which is used to display the prompt page to the user when an error occurs

onReceivedSslError()

Function: process the request

WebView does not process the HTTPS request by default, and the page is blank

webView.setWebViewClient (new WebViewClient() {

  1. Webchromeclient class

Function: assist WebView to process JavaScript dialog box, website icon, website title, etc.

Common methods

Common methods:

onProgressChanged()

Function: get the loading progress of the web page and display it

webview.setWebChromeClient(new WebChromeClient(){
					@Override

					public void onProgressChanged(WebView view, int newProgress) {
					if (newProgress < 100) {
						String progress = newProgress + "%";

						progress.setText(progress);

						} else {
						progress.setText(“100%”);

						}

						});

onReceivedTitle()

Function: get the title of the web page

Each page has a title, such as www.baidu.com The title of this page is “Baidu, you will know”, so how to know the title of the page being loaded by WebView and set it?

webview.setWebChromeClient(new WebChromeClient(){
						@Override

						public void onReceivedTitle(WebView view, String title) {
						titleview.setText(title);

						}

1.2.2.3 interaction between WebView and JavaScript

Note: how to avoid memory leaks in WebView?

It is recommended not to define WebView control in getapplicationgcontext() of XML layout file, but to create it directly in activity when necessary, and context object is recommended

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

						webView = new WebView(getApplicationContext());

						webView.setLayoutParams(params);

						mLayout.addView(webView);

When activity destroys (WebView), first let WebView load null content, then remove WebView, then destroy WebView, and finally set WebView to null.

@Override

						protected void onDestroy() {
						if (webView != null) {
						webView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);

						webView.clearHistory(); ((ViewGroup)

						webView.getParent()).removeView(mWebView);

						webView.destroy();

						webView = null;

						}

						super.onDestroy();

						}

example:

Objective: to achieve display“ www.baidu.com ”And get the title, start loading prompt, get loading progress and end loading prompt.

Concrete realization

The running display is as follows:


image

Step 1: in the AndroidManifest.xml Add network permissions to the manifest file


Step 2: layout file

<?xml version="1.0" encoding="utf-8"?>
							
								
								
								
								
								
							
					

Step 3: according to the required functions, call and use the corresponding subclass and its methods

public class WebViewActivity extends AppCompatActivity {