Calling Android native method via JS

Source: Internet
Author: User

Sometimes we have a need to listen to some of the events of the controls in the HTML. For example, click a button in the HTML to jump to another activity and copy a paragraph of text.
The first is the setting for WebView:

Mywebview = (WebView) Findviewbyid (R.id.mywebview);        Mywebview.getsettings (). setjavascriptenabled (true);        Mywebview.addjavascriptinterface (new javascriptinterface (this),                "Android" );        Mywebview.setwebviewclient (new mywebviewclient ());

To create the Javascriptinterface class:

 Public class Javascriptinterface {    context context;      Public javascriptinterface (context c) {        context= c;    }     /**      * The method used to interact with JS, in JS directly call the      */    @JavascriptInterface      publicvoid  showtoast (String ssss) {        toast.maketext (Mcontext, SSSs, Toast.length_long). Show ();    }}

Add @javascriptinterface annotations to a method that allows JS to be called in a higher version
Then use WebView's addjavascriptinterface to add the object of this class and take a name.

<script type= "Text/javascript" >   function  showtoast () {           android.showtoast ("haha aha" );     } </script>     onClick= "showtoast ()"/ ></body>

The HTML code is simple, and the native method can be successfully invoked using Android.shwotoast ("") in the JS method that wants to invoke the native method. We can use it to copy information, get click events, and so on. (Shwotoast is the native method name, and Android is the name we define in the Addjavascriptinterface method).

From:im mi

Calling Android native method via JS

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.