JavaScript and Java Communication

Source: Internet
Author: User

1. JavaScript in WebView calls the Android program in Java:

Using the Addjavascriptinterface () method in the WebView class, you can use it to extend the DOM (Document Object model) within an embedded browser and define new objects that JavaScript code can access. When JavaScript code calls the method of the object, it actually calls the method in the Android program.


2. Call the JavaScript method in the Android program:

Call the Loadurl () method to pass the URL to it in the form of javascript: The code to execute . Instead of going to a new page, the browser executes the given JavaScript expression on the current page.


Instance:


Build an Android program with the following layout (Res/layout/activity_local_browser.xml)

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Fill_parent "android:layout_height=" fill_parent "android:orientation=" vertical "&G    T <webview android:id= "@+id/web_view" android:layout_width= "fill_parent" android:layout_height= "fill _parent "android:layout_weight=" 1.0 "/> <linearlayout android:layout_width=" Fill_parent "and roid:layout_height= "Fill_parent" android:layout_weight= "1.0" android:orientation= "vertical" > < TextView android:id= "@+id/url_field" android:layout_width= "Fill_parent" android:layout_he            ight= "Wrap_content" android:text= "@string/textview"/> <button android:id= "@+id/button" Android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:text= "@s Tring/call_javascript_from_anDroid "/> <textview android:id=" @+id/text_view "android:layout_width=" Fill_parent " android:layout_height= "Wrap_content"/> </LinearLayout></LinearLayout>
As you can see, the top half of the layout is the Weview control, and the next part is the TextView and button from the Android user interface.

Below you need to complete the index.html file (assets/index.html) that will be loaded into WebView, the code is as follows

As you can see, the Calljs () function is a JavaScript function that will be called in Java code, which takes a parameter and assigns a value to the replaceme tag. The next two links are the Callandroid () methods (defined in Java code) that call the Window.alert () function (which shows the short message) and the Window.android object.

Also do not forget to complete the assignment of the string in the Res/values/strings.xml file:

<?xml version= "1.0" encoding= "Utf-8"?><resources>    <string name= "App_name" >localbrower</ string>    <string name= "action_settings" >Settings</string>    <string name= "TextView" > textview</string>    <string name= "Call_javascript_from_android" >call JavaScript from android</ String></resources>


After completing these preparations, you can put your eyes on the Localbrowser class of the program, the code is as follows:

Package Com.example.localbrowser;import Android.support.v7.app.actionbaractivity;import Android.annotation.suppresslint;import Android.os.bundle;import Android.os.handler;import Android.view.Menu; Import Android.view.menuitem;import Android.view.view;import Android.view.view.onclicklistener;import Android.webkit.javascriptinterface;import Android.webkit.jsresult;import Android.webkit.webview;import Android.webkit.webchromeclient;import Android.widget.button;import Android.widget.textview;import Android.widget.Toast, @SuppressLint ("Javascriptinterface") public class Localbrowser extends Actionbaractivity { Private WebView webview;private Button button;private TextView textview;private final Handler Handler = new Handler (); @Ove rrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_local_browser) WebView = (WebView) Findviewbyid (r.id.web_view); button = (Button) Findviewbyid ( R.id.button); TextView = (TextView) Findviewbyid (R.Id.text_view) Button.setonclicklistener (new Onclicklistener () {public void OnClick (view view) {///click the button, Call the Calljs () function defined in index.html through the Webview.loadurl () method Webview.loadurl ("Javascript:calljs (' Hello from Android ')");}); /open JavaScript (default is OFF) webview.getsettings (). Setjavascriptenabled (true);//Inject Java objects into WebView, This allows the method to use this object in Index.tml webview.addjavascriptinterface (New Androidbridge (), "Android"); Webview.setwebchromeclient (New Webchromeclient () {//Overrides the default Window.alert () display Interface public boolean Onjsalert (final WebView View, final string url,final string message, jsresult result) {Toast.maketext (localbrowser.this, Message,.). Show (); Result.confirm (); return true;}); Webview.loadurl ("file:///android_asset/index.html");//Load local page, note there are 3 slashes}public class Androidbridge {@ javascriptinterface//Java code fragment to be called via JavaScript public void callandroid (final String Arg) {handler.post (new Runnable () { public void Run () {textview.settext (ARG);}});}}

The whole process is simple, but it's a little bit important to note:

In the Adroidbridge class

The interfaces exposed by the object injected to WebView before 4.2 callandroid have no comment statement @javascriptinterface, and 4.2 and later have more comment statement @javascriptinterface. If you remove this line of code, when the program calls this method, it will not succeed, and Logcat will report the following output:

e/web console:uncaught Typeerror:object [Object Object] has no method ' callandroid '


Program Interface:



When you click a button and a link, it is called between the two environments, with the following running









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.