Try Android and JS interaction

Source: Internet
Author: User

Use WebView to invoke the JS code on the Web page in 1.android.

Android can be implemented by WebView and JS Interaction, in the program to invoke the JS code, only the WebView control of the support JS property set to True, and then through the Loadurl can be directly called, as follows:

Mwebview.getsettings (). Setjavascriptenabled (True);

Mwebview.loadurl ("Javascript:test ()");

2. How to invoke Java code in Android on a Web page

Calling Java code in a Web page requires adding javascriptinterface to the WebView control. As shown below:

Mwebview.addjavascriptinterface (New Object () {

public void Clickonandroid () {

Mhandler.post (New Runnable () {

public void Run () {

Toast.maketext (test.this, "Test call Java", Toast.length_long). Show ();

}

});

}

}, "demo");

In the Web page, just like invoking the JS method, the call can be

<div id= ' B ' ><a onclick= "window.demo.clickOnAndroid ()" >b.c</a></div>

3. Java code calls JS and passes the parameter

First you need a JS function with parameters, such as function Test (str), and then simply pass in the parameters when you call JS, as follows:

Mwebview.loadurl ("Javascript:test (' AA ')");

Call Java functions and pass parameters in 4.Js

First, you need the function form with parameters, but be aware that the parameter here requires the final type, that is, you can not modify it later, if you need to modify the value, you may set the intermediate variable, and then modify. As shown below:

Mwebview.addjavascriptinterface (New Object () {

public void clickonandroid (final int i) {

Mhandler.post (New Runnable () {

public void Run () {

int j = i;

j + +;

Toast.maketext (test.this, "Test call Java" + string.valueof (j), Toast.length_long). Show ();

}

});

}

}, "demo");

Then in the HTML page, use the following code <div id= ' B ' ><a onclick= "window.demo.clickOnAndroid (2)" >B.C</A></DIV>

Try Android and JS interaction

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.