Communication between JavaScript and Java, javascriptjava
1. JavaScript in WebView calls Java in Android:
The addJavascriptInterface () method in the WebView class can be used to extend the DOM (Document Object Model) in the embedded browser and define new objects that can be accessed by JavaScript code. When JavaScript code calls the method of this object, it actually calls the method in the Android program.
2. Call the JavaScript method in the Android program:
Call the loadUrl () method to convert the URL to javascript:Code to be executedTo It. The browser will execute the given JavaScript expression on the current page, instead of going to the new 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" > <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" android: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_height="wrap_content" android:text="@string/textview"/> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/call_javascript_from_android" /> <TextView android:id="@+id/text_view" android:layout_width="fill_parent" android:layout_height="wrap_content"/> </LinearLayout></LinearLayout>
We can see that the upper part of the layout is the WeView control, and the lower part is the TextView and Button from the Android user interface.
The following code will be uploaded to the index.html file (assets/index.html) in webview.
As you can see, the callJS () function is called by the JavaScript function in Java code. It receives a parameter and assigns the value to the replaceme tag. The following two links call the callAndroid () method of the window. alert () function (displaying short messages) and window. android object (defined in Java code ).
Do not forget to assign values to strings 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 focus 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 (); @ Overrideprotected 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) {// when the single-click button is enabled, call webview.loadurl(callback callback to call the callJS () function webview defined in index.html. loadUrl ("javascript: callJS ('Hello from android')") ;}}); // open JavaScript (disabled by default) webview. getSettings (). setJavaScriptEnabled (true); // inject a Java object to the WebView so that. the method webview that can use this object in tml. addJavascriptInterface (new AndroidBridge (), "android"); webview. setWebChromeClient (new WebChromeClient () {// overwrite 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, 3000 ). show (); result. confirm (); return true ;}}); webview. loadUrl ("file: // android_asset/index.html"); // load the local webpage, note that there are 3 slashes} public class AndroidBridge {@ JavascriptInterface // Java code snippet to be called through JavaScript public void callAndroid (final String arg) {handler. post (new Runnable () {public void run () {textview. setText (arg );}});}}}
The process is simple, but note that:
In the AdroidBridge class
The interface callAndroid exposed to objects injected to WebView before 4.2 has no comment statement @ JavascriptInterface, while the comment statement @ JavascriptInterface is added to the interface 4.2 and later. If this line of code is removed, the program fails to call this method, and logcat reports the following output:
E/Web Console: Uncaught TypeError: Object [object Object] has no method 'callandroid'
Program interface:
When you click the button and link, it is called between two environments. below is the running
Differences between java and javascript
Although JavaScript is closely related to Java, it is two different products developed by two companies. Java is a new-generation object-oriented programming language released by SUN, which is especially suitable for Internet application development. JavaScript is a product of Netscape, and its purpose is to expand the Netscape Navigator function, developed an object-and event-driven explanatory language that can be embedded into Web pages, its predecessor is Live Script, and Java's predecessor is the Oak language. The similarities and differences between the two languages are compared as follows:
Object-based and object-oriented
Java is a real object-oriented language. Even a simple program must be designed.
JavaScript is a scripting language that can be used to create complex software that is unrelated to the network and interacts with users. It is an Object-Based and Event Driver-Based programming language. Therefore, it provides a wide range of internal objects for designers.
Interpretation and compilation
The two languages are executed in different ways in their browsers. Java source code must be compiled before it is passed to the client for execution. Therefore, the client must have a simulator or interpreter on the corresponding platform, it can use compilers or interpreters to compile code independently from a specific platform.
JavaScript is an interpreted programming language. Its source code does not need to be compiled before it is sent to the client for execution. Instead, it sends the character code in the text format to the client for interpretation and execution by the browser.
Strong variables and weak Variables
The variables used by the two languages are different.
Java uses a strongly typed variable check, that is, all variables must be declared before compilation. For example:
Integer x;
String y;
X = 1234;
X = 4321;
X = 1234 indicates an integer, and Y = 4321 indicates a string.
The variable declaration in JavaScript uses its weak type. That is, variables do not need to be declared before use, but the interpreter checks their data types at runtime, such:
X = 1234;
Y = "4321 ";
The former indicates that x is its numeric variable, while the latter indicates that y is a numeric variable.
Different Code formats
Java is an HTML-independent format. It must be loaded by referencing external media in HTML, and its code is saved as byte code in an independent document.
JavaScript code is a text character format that can be directly embedded into HTML documents and loaded dynamically. Compiling HTML documents is as convenient as editing text files.
Different embedding Methods
In HTML documents, the two programming languages have different identities. JavaScript uses <Script>... </Script>, while Java uses <applet>... </applet>.
Static Association and Dynamic Association
Java uses static concatenation, that is, Java object reference must be carried out during compilation, so that the compiler can implement forced type check.
JavaScript uses dynamic concatenation, that is, JavaScript Object Reference is checked at runtime. If it is not compiled, the object reference check cannot be implemented.
What is the difference between JavaScript and Java?
JavaScript is an embedded script file that is directly inserted into a webpage and executed by a browser while interpreting it.
The java language is different. It must run on the java Virtual Machine. Compilation is required in advance.
JAVA has more strict syntax rules than JavaScript, and more powerful functions.