WebView introduction and simple method to realize Android and H5 intermodulation

Why learn Android and H5 intermodulation?

A large number of software such as wechat and QQ space are embedded with H5, which is a trend. Android and H5 intermodulation can enable us to realize mixed development. As for mixed development, a lightweight browser is embedded in an app, and some native functions are developed by HTML 5.

Advantages: the functions implemented with H5 can be dynamically updated without upgrading the app, and can run simultaneously on Android or IOS apps, saving costs and improving development efficiency.

Principle: it is actually a call between Java code and JavaScript.

Insert the directory structure of an article at the beginning:

Introduction to WebView

To realize the intermodulation between Android and H5, WebView is a very important control. WebView can help us display HTML pages, so it is necessary to learn about WebView first.

I. common methods of WebView

loadUrl

The loading interface is followed by the loaddata and loaddatawithbase methods

Setwebviewclient (if the user sets webviewclient, after clicking the new link, it will not jump to the system browser, but will be displayed in this WebView. Note: it is not necessary to override shoulderoverrideurloading method, and all links can be opened in WebView.)

Webviewclient is mainly used to assist WebView in handling various notifications, requests and other events. It is set through setwebviewclient method. Here are some common uses:

Realize the interception of hyperlinks in web pages (for example, if it is the home page of geek navigation, directly intercept and go to Baidu home page):

After clicking the link in the page, the shouldoverrideurloading (WebView, string URL) method will be called back before WebView loads the URL. Generally, click a link and this method will be called once.

Misunderstanding about the return value of shouldoverrideurlloading: many online explanations are that return true means to open the link in this WebView, and return false means to call the system browser to open the link. In fact, as long as webviewclient is set, the system browser will not be called.

So what exactly does the return value of shouldoverrideurlloading represent? Return true, WebView will not load the new URL when it is opened. All processing needs to be performed in WebView, including loading; Return false, the system considers that the upper layer has not processed it, and will continue to load the URL next; The default return is false. The specific differences are shown as follows:

After loading Baidu homepage and setting webviewclient, rewrite shouldoverrideurlloading (WebView, string URL) method. The first one is a screenshot that returns false (jump normally after clicking), and the second chapter is a screenshot that returns true (click no response, if you want to jump, we need to deal with it ourselves):

Another thing to note is that if we intercept a URL, there is little difference between return false and return true, so it is generally recommended to return false.

Replace a resource when loading a web page (for example, when loading a web page, we need to load a logo image, and we want to replace this logo image with an image in our assets directory)

We know that when we load a web page, we will also load JS, CSS, pictures and other resources, so we will call shouldinterceptrequest method many times. We can replace pictures in shouldinceptrequest.

Note: shouldinterceptrequest has two overloads:

① Public webresourceresponse shouldinterceptrequest (WebView, string URL) [obsolete]

②public WebResourceResponse shouldInterceptRequest (WebView view,WebResourceRequest request)

These two methods are mainly different from the second parameter. Webresourcerequest will be able to obtain more information. Geturl (), getmethod, getrequestheaders and other methods are provided. The first callback method is used to show the effect. The implementation method is as follows:

Set the start of loading web pages, the completion of loading, and the handling of loading errors

Process HTTPS requests and set SSL certificates for WebView. WebView does not process HTTPS requests by default. You need to override the onreceivedsslerror function of the parent class in the webviewclient subclass

setWebChromeClient

Webchromeclient is mainly used to assist WebView in handling JavaScript dialog boxes, website icons, website titles, web page loading progress, etc. Set through the setwebchromeclient() method of WebView.

Display the page loading progress. Override the onprogresschanged function of the parent class in the webchromeclient subclass. Progress represents the current page loading progress, which is an integer from 1 to 100

Speed up the completion of HTML page loading (by default, after the HTML code is downloaded to WebView, the WebKit starts to parse each node of the web page. When an external style file or external script file is found, it will asynchronously initiate a network request to download the file. However, if the HTML code is also parsed to the image node before that, it will also initiate a network request to download the corresponding picture. In the case of poor network conditions, there are too many network requests It will cause bandwidth tension, affect the time of CSS or JS file loading, and cause page blank loading for too long. The solution is to tell WebView not to automatically load images first, and then initiate image loading after the page is finished.)

setDownloadListener

Usually, the interface rendered by WebView contains a link to download files. After clicking the link, you should start downloading and save the files to the local.

Create downloadlistener

Add monitoring to WebView

goBack()

Return to the previous browsing page, and click the return button to return to the previous browsing page instead of exiting the program by overriding the onkeydown method

II. Websettings configuration

Get websettings object

Common setting methods

(1) Support JS

(2) There are several cache settings:

LOAD_ CACHE_ Only: do not use the network, only read the local cache data.

LOAD_ Default: determines whether to fetch data from the network according to cache control.

LOAD_ CACHE_ Normal: API level 17 has been abandoned. Starting from API level 11, it works the same as load_ Default mode.

LOAD_ NO_ Cache: do not use cache, only get data from the network.

LOAD_ CACHE_ ELSE_ Network: as long as there is a local cache, the data in the cache is used regardless of whether it is expired or no cache.

(3) Open the DOM storage API function (a standard interface provided by HTML5, which mainly stores key value pairs locally. After the page is loaded, you can operate these data through JavaScript.)

(4) Set database cache path

(5) Set application caches cache directory

(6) Set default encoding

(7) Resize the picture to fit the WebView

(8) Support scaling

(9) Support content re layout

(10) Multi window

(11) Set access to files

(12) Set the node for WebView when WebView calls requestfocus

(13) Settings support scaling

(14) Support opening new windows through JS

(15) Zoom to screen size

(16) Support automatic loading of pictures

III. list of callback methods of webviewclient

Webviewclient is mainly used to assist WebView in handling various notifications, requests and other events. It is set through setwebviewclient method.

(1) Update history

(2) The application re requests web page data

(3) It will be called when loading page resources, and each resource (such as pictures) will be called once.

(4) Start loading the page call. Usually, we can set a loading page here to tell the user that the program is waiting for the network response.

(5) Called at the end of page loading. Similarly, we know that a page is loaded, so we can close the loading bar and switch the program action.

(6) Report error messages

(7) Get return information authorization request

(8) Overriding this method allows WebView to process HTTPS requests.

(9) Called when the WebView changes

(10) Called when the key event is not loaded

(11) Override this method to handle key events in the browser.

(12) Call this function when the web page jumps. We can do many operations. For example, we read some special URLs, so we can cancel this operation without opening the address and carry out other predefined operations, which is very necessary for a program.

(13) Called multiple times when loading the resources of a web page (obsolete)

(14) Called multiple times when loading the resources of a web page

be careful:

IV. list of callback methods of webcolomeclient

Webchromeclient is mainly used to assist WebView in handling JavaScript dialog boxes, website icons, website titles, web page loading progress, etc. Set through the setwebchromeclient() method of WebView.

(1) Monitor web page loading progress

(2) Monitor web page title: for example, the title of Baidu page is "Baidu, you know"

(3) Listen web Icon

Java and JavaScript intermodulation

For ease of presentation, the addjavascript interface is used to interact with the local JS (there is a vulnerability). It can also be implemented in other ways, such as intercepting ur, parameter parsing L, etc.

Java tune JS

The first is a section of JS code:

Then we call the method in JS in Java.

The above code calls a method called javacalljs (ARG) in JS and passes in a name parameter. (specific effects are shown below)

JS calling Java

Configuring JavaScript interfaces

Implement JavaScript interface classes

Calling java code in JS

"Android" in window.android.showtoast ('parameter passed from JS'), that is, specified in addjavascriptinterface(), and JS passed the parameter to Java, with the type of string. Showtoast (string ARG) will pop up this parameter in the form of toast.

Java and JS intermodulation code example

Look at the renderings first:

The code is very simple and annotated. Just look at the code directly.

The first is the local javaandjavascript call.html file, which is placed in the asstes directory

Javacalljs is the method that Java calls JS, and showtoast is the method that JS calls Java

Next is the layout file, activity_ main.xml

It's very simple. It's an input box and an OK button. Clicking the button will call the methods in JS.

MainActivity

Points needing attention

Reference link: some pits of Android WebView

Save status

Restore state (in oncreate (bundle savedinstancestate) of activity)

Other frequently asked questions:

1. WebViewClient.onPageFinished()。

You can never be sure whether the web content is really loaded when WebView calls this method. This method may be called many times when the currently loaded web page jumps. There is a specific explanation on stackoverflow (how to listen for a WebView finishing loading a URL in Android?), but the solutions listed therein are not perfect. Therefore, when your WebView needs to load various web pages and take some actions when the page is loaded, webchromeclient. Onprogresschanged() may be more reliable than webviewclient. Onpagefinished().

2. WebView background power consumption.

When your program calls WebView to load web pages, WebView will start some threads (?) by itself. If you do not destroy WebView correctly, these residual threads (?) will always run in the background, resulting in high power consumption of your application. The processing method I adopt is lazy, simple and rough (not recommended), that is, directly call system. Exit (0) in activity. Ondestroy() to completely remove the application from the virtual machine, so that there will be no problems.

3. The problem of switching WebView flash screen.

If you need to switch back and forth between different webviews (including different web content) in the same ViewGroup, you will find that flashing is inevitable. This should be the bug of Android hardware acceleration. If you turn off hardware acceleration, the situation will be much better, but you can't get a good browsing experience. You will feel that the web page slides one card at a time.

4. On some mobile phones, when WebView has videos, after the activity is destroyed, the video resources are not destroyed, and even can be heard playing in the background. Even destroying webviews like just now won't help. The solution: change the URL to an empty address before ondestory.

5. WebView hardware acceleration causes page rendering flicker

About Android hardware acceleration, it began with Android 3.0 (API level 11). After hardware acceleration is turned on, WebView renders pages faster and drags more smoothly. However, one side effect is that it is easy to load white blocks on the page and the interface flashes at the same time. The solution to this problem is to set WebView to temporarily turn off hardware acceleration. The code is as follows:

summary

The above is the whole content of this article. I hope the content of this article has a certain reference value for your study or work. If you have any questions, you can leave a message. Thank you for your support for programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>