Using JS to interact with Java

Source: Internet
Author: User

To facilitate web and application interaction, the Android system WebView provides a mechanism for JavaScript Web script to invoke Java class methods. You can map a Java object to a JavaScript object as long as you call the Addjavascriptinterface method.

Mainactivity.java Code:

Package Com.apple.browser;import Android.annotation.suppresslint;import Android.app.activity;import Android.os.bundle;import Android.view.menu;import Android.webkit.websettings;import Android.webkit.WebView;import Android.widget.toast;public class Mainactivity extends activity {private WebView webview;private activity activity;@ Suppresslint ("setjavascriptenabled") @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (r.layout.activity_main); activity = This;webview = (webView) Findviewbyid ( R.id.webview); Webview.loadurl ("file:///android_asset/index.html"); final websettings settings = webview.getsettings (); settings.setjavascriptcanopenwindowsautomatically (true); settings.setjavascriptenabled (true); Settings.setsupportzoom (True); Webview.addjavascriptinterface (new Jsinvokeclass (), "Js2java");} Public final class Jsinvokeclass {public void back () {//Activity.finish (); Toast.maketext (Activity, "Java method called by JS", Toast.length_short). Show ();}} 


Code in HTML:

<input Type=button name=smt value= ' invoke Java ' onclick= "Javascript:window.js2java.back ();" >


XML Layout Code:
Slightly

Using JS to interact with Java

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.