JS and iOS, Android interaction

Source: Internet
Author: User

First, JS and Android

Placed under the Assets folder (note that if you are using as the Ide,assets folder should be placed in the Src/main directory)

<!DOCTYPE HTML><HTML>   <Head>      <MetaCharSet= "Utf-8">      <title>Geff</title>            <Script>         functioncallandroid () {Test.hello ("JS calls the Hello method in Android"); }      </Script>   </Head>   <Body>      <Buttontype= "button"ID= "Button1"onclick= "callandroid ()">JS calls the code in Android</Button>   </Body></HTML>

The code is very simple, the page is a button, click on this button to call the Callandroid function, it is important to note that the statement in the Callandroid function is an external function of Android, the code in Android:

{    ...       Websettings.setjavascriptenabled (true);    Webview.addjavascriptinterface (This, "test"); // corresponding to the test.xxx    in JS Webview.loadurl ("file:///android_asset/js_web.html");} @JavascriptInterfacepublicvoid Hello (String msg) {// corresponds to JS in Xxx.hello ("" )    log.e ("WebView", "Hello");    Toast.maketext (this, Msg,toast.length_long). Show ();}

It is important to note that the Hello function plus the annotation @javascriptinterface, so clicking on the button in the HTML will invoke the Hello method in Android.

Second, the Android call JS code

The JS code is as follows:

<script>   function  calljs () {      alert ("Android calls the Calljs method in JS");   } </script>

The Android code is as follows:

void Click (View view) {    webview.post (new  Runnable () {        @Override        void  Run () {            Webview.loadurl ("Javascript:calljs ()");        }    });

When the button in Android is clicked, the click Method is triggered, then the Webview.loadurl ("Javascript:calljs ()") is executed, then the Calljs method is exactly the same in JS, then the alert () is executed.

This concludes very well:

Https://github.com/shaojiankui/iOS-WebView-JavaScript

JS and iOS, Android 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.