The way to implement JavaScript invoke Java classes in WebView in Android _android

Source: Internet
Author: User

To facilitate interaction between Web pages and Android apps, the Android system provides a mechanism for invoking Java class methods in WebView JavaScript Web scripts. You can map a Java object to a JavaScript object as long as you call the Addjavascriptinterface method.

1. Mapping Java objects to JavaScript objects

Copy Code code as follows:

Mwebview = (webview) Findviewbyid (r.id.wv_content);
Mwebview.setverticalscrollbaroverlay (TRUE);
Final websettings settings = Mwebview.getsettings ();
Settings.setsupportzoom (TRUE);

WebView Enable JavaScript script execution
Settings.setjavascriptenabled (TRUE);
Settings.setjavascriptcanopenwindowsautomatically (TRUE);

Map Java objects to a JavaScript object named "Js2java"
Methods for invoking Java objects through "Window.js2java" in JavaScript
Mwebview.addjavascriptinterface (New Jsinvokeclass (), "Js2java");

Copy Code code as follows:

/** Web page JavaScript invoke interface **/
Class Jsinvokeclass {
public void back () {
Activity.finish ();
}
}

2. JavaScript invoke Java Object Example

Invoke the back method of the above Jsinvokeclass class object, as follows:

Copy Code code as follows:

Window.js2java.back ();

Related Article

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.