Two ways for Android to realize H5 and native interaction

preface

As we all know, in the use of Android WebView, H5 page and native page often need to interact. For example, click the share button on the web page and call the local sharing interface to share. After successful sharing, call the JavaScript code of the web page locally to display a message of successful sharing. Let's take a look at the two implementations?

1、 Method of URL interception

Rewrite shouldoverrideurl for URL interception. In this way, the URL format negotiated between H5 and native indicates the operations that H5 page wants native to perform, such as making a phone call, playing a video, viewing a user's information, etc. each operation corresponds to a URL format, such as:

Parameters can be passed through the parameter of the URL and parsed through uri.parse. Return true to truncate the response to the URL request.

2、 JavaScript injection mode

Compared with the method of URL interception, JavaScript injection is more direct. Native injects functions open to H5 calls into JavaScript, and H5 calls native functions through JavaScript to complete the operation.

1. Get the webviewsettings setting of WebView and call setjavascript enabled to start JavaScript call.

2. Add the @ javascriptinterface annotation in front of the function that needs to be exposed to JavaScript. Only the function with this annotation can be called by JavaScript.

3. Inject the class of the native method into JavaScript through the addjavascriptinterface method of WebView. The first parameter of the function is the injected native object, and the second parameter is the name of the object. JavaScript accesses the object by changing its name

4. In this way, the H5 page can call the native function through the following JavaScript

Native calls JavaScript

Native calls JavaScript functions simply by using the loadurl function:

summary

The above is the whole content of this article. I hope the content of this article can bring some help to Android developers. If you have any questions, you can leave a message.

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
分享
二维码
< <上一篇
下一篇>>