JavaScript calls Java and javascriptjava

Source: Internet
Author: User

JavaScript calls Java and javascriptjava

1. Map a Java object to a JavaScript Object

MainActivity. java

Package com. example. jsdemo; import android. OS. bundle; import android. support. v7.app. appCompatActivity; import android. webkit. webSettings; import android. webkit. webView; public class MainActivity extends AppCompatActivity {private WebView wView; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); wView = (WebView) findViewById (R. id. wView); wView. loadUrl ("file: // android_asset/demo1.html"); WebSettings webSettings = wView. getSettings (); // ① set WebView to allow the call of js webSettings. setJavaScriptEnabled (true); webSettings. setDefaultTextEncodingName ("UTF-8"); // sets support for js calls java wView. addJavascriptInterface (new AndroidAndJSInterface (), "Android" ");} class AndroidAndJSInterface {@ JavascriptInterface public void showToast () {Toast. makeText (MainActivity. this, "I have been called by js", Toast. LENGTH_SHORT ). show ();}}}

Note: The WebView. addJavascriptInterface interface does not work in two ways.

① Change the version to 16

(2) Add the @ JavascriptInterface annotation to the method of the JavaScript interface class.

2. Example of JavaScript calling a Java object

Demo1.html

<Input type = "button" value = "Click Android to be called" onclick = "window. Android. showToast ()"/>

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.