JS interaction between Android and H5

Source: Internet
Author: User

Before the project did some of the JS interaction between Android and HTML5 things, today there is time to summarize:

First, why to do JS interaction:

In order to facilitate native development and data transfer between HTML, in the case of static pages can change the original development of the page;

Second, how to do JS interaction:

(i) The Android side calls the H5 page

The main use of WebView on the Android side for Web page loading, setting properties

// Get Websetting Object WebSettings websettings = webview.getsettings (); // set support JavaScriptwebsettings.setjavascriptenabled (true); // The class object defined in Android Androidjs exposed to JavaScript
Webview.addjavascriptinterface (new Androidjs (mainactivity. this"androidjs");

How to call: where DoAlert is the H5 page method

Webview.loadurl ("javascript:doalert ()");

(ii) H5 end call Android page

H5-Side code:

<input type="button" value=" greeting  " onclick="  Androidjs.showtoast ()"/><input type="button" value="  Book list " onclick="androidjs.showlist ()"/>

Android Side code:

 Public classAndroidjs {PrivateContext Mcontext;  PublicAndroidjs (Context context) { This. Mcontext =context; } @JavascriptInterface Public voidshowlist () {NewAlertdialog.builder (Mcontext). Settitle ("List of Books"). SetIcon (R.mipmap.ic_launcher). Setitems (Newstring[]{"Crazy Java Handouts","Crazy Android Handout",                                "lightweight Java EE Development"},NULL). Setpositivebutton ("Determine",NULL). Create (). Show (); } @JavascriptInterface Public voidShowtoast () {Toast.maketext (Mcontext,"Hello", Toast.length_long). Show (); }}

Note: Androidjs is a bridge identifier that connects Android with HTML, and is also a class for interacting with the data;

Note: The method in this must be common, and the class name is consistent with the identity;

The above is a simple JS interactive process, note the place to pay special attention, please advise

JS interaction between Android and H5

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.