Table of Contents
How to implement
This example code
Calling example
js calls Java
Java calls JS
Function" >Calling js without parameters and no return valueFunction
Call js function with parameters and no return value
Calling js functions with parameters and return values
4.4 Processing
Question Answers
Alert cannot pop up" >Alert cannot pop up
Uncaught ReferenceError: functionName is not defined" >Uncaught ReferenceError: functionName is not defined
Uncaught TypeError: Object [object Object] has no method" >Uncaught TypeError: Object [object Object] has no method
Security restriction issue
Two solutions
Code obfuscation problem
All WebView methods must be called on the same thread" >All WebView methods must be called on the same thread
Home Web Front-end JS Tutorial Detailed explanation of Java and JavaScript interaction in Android

Detailed explanation of Java and JavaScript interaction in Android

Mar 15, 2017 pm 05:30 PM

Android provides a very powerful WebView control for processing Web pages, and in the web page, JavaScript is also a very important script. This article will introduce how to implement mutual calls between Java code and Javascript code.

How to implement

It is very convenient to realize the interaction between Java and js. Usually only the following steps are required.

  • WebView enables JavaScript script execution

  • WebView sets the interactive interface for JavaScript calls.

  • The client and the web page write code to call each other.

This example code

For the convenience of explanation, all the code is posted first

Java code

package com.example.javajsinteractiondemo;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class MainActivity extends Activity {
  private static final String LOGTAG = "MainActivity";
  @SuppressLint("JavascriptInterface")
  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      final WebView myWebView = (WebView) findViewById(R.id.myWebView);
      WebSettings settings = myWebView.getSettings();
      settings.setJavaScriptEnabled(true);
      myWebView.addJavascriptInterface(new JsInteration(), "control");
      myWebView.setWebChromeClient(new WebChromeClient() {});
      myWebView.setWebViewClient(new WebViewClient() {

          @Override
          public void onPageFinished(WebView view, String url) {
              super.onPageFinished(view, url);
              testMethod(myWebView);
          }

      });
      myWebView.loadUrl("file:///android_asset/js_java_interaction.html");
  }

  private void testMethod(WebView webView) {
      String call = "javascript:sayHello()";

      call = "javascript:alertMessage(\"" + "content" + "\")";

      call = "javascript:toastMessage(\"" + "content" + "\")";

      call = "javascript:sumToJava(1,2)";
      webView.loadUrl(call);

  }

  public class JsInteration {

      @JavascriptInterface
      public void toastMessage(String message) {
          Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
      }

      @JavascriptInterface
      public void onSumResult(int result) {
          Log.i(LOGTAG, "onSumResult result=" + result);
      }
  }

}
Copy after login

Front-end web page code

<html>
<script type="text/javascript">
    function sayHello() {
        alert("Hello")
    }

    function alertMessage(message) {
        alert(message)
    }

    function toastMessage(message) {
        window.control.toastMessage(message)
    }

    function sumToJava(number1, number2){
       window.control.onSumResult(number1 + number2)
    }
</script>
Java-Javascript Interaction In Android
</html>
Copy after login

Calling example

js calls Java

The calling format is window.jsInterfaceName.methodName(parameterValues) In this example we use control as the injection interface name.

function toastMessage(message) {
  window.control.toastMessage(message)
}

function sumToJava(number1, number2){
   window.control.onSumResult(number1 + number2)
}
Copy after login

Java calls JS

The basic format of webView calling js is webView.loadUrl("javascript:methodName(parameterValues)")

Calling js without parameters and no return valueFunction

String call = "javascript:sayHello()";
webView.loadUrl(call);
Copy after login

Call js function with parameters and no return value

Note that strings need to be escaped in double quotes as parameter values.

String call = "javascript:alertMessage(\"" + "content" + "\")";
webView.loadUrl(call);
Copy after login

Calling js functions with parameters and return values

Before 4.4, Android did not provide a method to directly call js functions and obtain values, so before that, the common idea was to call java js method, after the js method is executed, call the java code again to return the value.

1.Java calls js code

String call = "javascript:sumToJava(1,2)";
webView.loadUrl(call);
Copy after login

2.js function processing and returns the result by calling the java method

function sumToJava(number1, number2){
       window.control.onSumResult(number1 + number2)
}
Copy after login

3.Java obtains the js function in the callback method Return value

@JavascriptInterface
public void onSumResult(int result) {
  Log.i(LOGTAG, "onSumResult result=" + result);
}
Copy after login

4.4 Processing

Use evaluateJavascript after Android 4.4. Here is a simple interactive example of a js method with a return value

function getGreetings() {
      return 1;
}
Copy after login

Use the evaluateJavascript method to call when using java code

private void testEvaluateJavascript(WebView webView) {
  webView.evaluateJavascript("getGreetings()", new ValueCallback<String>() {

  @Override
  public void onReceiveValue(String value) {
      Log.i(LOGTAG, "onReceiveValue value=" + value);
  }});
}
Copy after login

Output results

I/MainActivity( 1432): onReceiveValue value=1
Copy after login

Note

  • The above limits the return result to String. For simple types, it will be converted into a string and returned. For complex data types, it is recommended to use the string form jsonreturn.

  • evaluateJavascript method must be called on the UI thread (main thread), so onReceiveValue is also executed on the main thread.

Question Answers

Alert cannot pop up

You should not have set up WebChromeClient, follow the following code to set it up

myWebView.setWebChromeClient(new WebChromeClient() {});
Copy after login

Uncaught ReferenceError: functionName is not defined

The reason for the problem is that the js code of the webpage has not been loaded, so the js method is called. The solution is to call the js method after the web page is loaded.

myWebView.setWebViewClient(new WebViewClient() {

  @Override
  public void onPageFinished(WebView view, String url) {
      super.onPageFinished(view, url);
      //在这里执行你想调用的js函数
  }

});
Copy after login

Uncaught TypeError: Object [object Object] has no method

Security restriction issue

If the problem only occurs on machines with version 4.2 or above, then the problem is that the system is under security restrictions. The Android documentation says this

Caution: If you've set your targetSdkVersion to 17 or higher, you must add the @JavascriptInterface annotation to any method that you want available your web page code (the method must also be public). If you do not provide the annotation, then the method will not accessible by your web page when running on Android 4.2 or higher.

中文译为

Warning: If your program targets platform 17 or higher, you must add @JavascriptInterface annotation to the method exposed to the web page callable (this method must be public). If you don't do this, the web page will not be able to access your method on platforms 4.2 and later.

Two solutions
  • Set targetSdkVersion to 17 or higher and introduce @JavascriptInterface annotation

  • Create an annotation interface named @JavascriptInterface yourself, and then import it. Note that this interface cannot be confused.

Note, create @JavascriptInterface code

public @interface JavascriptInterface {

}
Copy after login

Code obfuscation problem

If the code in the unobfuscated version runs normally, the code in the obfuscated version A running error occurs and the message Uncaught TypeError: Object [object Object] has no method means that you have not done any obfuscating exception handling. Add code similar to this to the obfuscation file

-keep class com.example.javajsinteractiondemo$JsInteration {
    *;
}
Copy after login

All WebView methods must be called on the same thread

Filter logs have discovered this problem.

E/StrictMode( 1546): java.lang.Throwable: A WebView method was called on thread &#39;JavaBridge&#39;. 
All WebView methods must be called on the same thread. (Expected Looper Looper (main, tid 1) {528712d4} called on Looper (JavaBridge, tid 121) {52b6678c}, 
FYI main Looper is Looper (main, tid 1) {528712d4})
E/StrictMode( 1546):   at android.webkit.WebView.checkThread(WebView.java:2063)
E/StrictMode( 1546):   at android.webkit.WebView.loadUrl(WebView.java:794)
E/StrictMode( 1546):   at com.xxx.xxxx.xxxx.xxxx.xxxxxxx$JavaScriptInterface.onCanGoBackResult(xxxx.java:96)
E/StrictMode( 1546):   at com.android.org.chromium.base.SystemMessageHandler.nativeDoRunLoopOnce(Native Method)
E/StrictMode( 1546):   at com.android.org.chromium.base.SystemMessageHandler.handleMessage(SystemMessageHandler.java:27)
E/StrictMode( 1546):   at android.os.Handler.dispatchMessage(Handler.java:102)
E/StrictMode( 1546):   at android.os.Looper.loop(Looper.java:136)
E/StrictMode( 1546):   at android.os.HandlerThread.run(HandlerThread.java:61)
Copy after login

The Java callback thread after the js call is not the main thread. If you print the log, you can verify

ThreadInfo=Thread[WebViewCoreThread,5,main]
Copy after login

To solve the above exception, just put the webview operation in the main thread.

webView.post(new Runnable() {
    @Override
    public void run() {
        webView.loadUrl(YOUR_URL).
    }
});
Copy after login


The above is the detailed content of Detailed explanation of Java and JavaScript interaction in Android. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Xiaomi Redmi Note 14 Pro Plus arrives as first Qualcomm Snapdragon 7s Gen 3 smartphone with Light Hunter 800 camera Xiaomi Redmi Note 14 Pro Plus arrives as first Qualcomm Snapdragon 7s Gen 3 smartphone with Light Hunter 800 camera Sep 27, 2024 am 06:23 AM

The Redmi Note 14 Pro Plus is now official as a direct successor to last year'sRedmi Note 13 Pro Plus(curr. $375 on Amazon). As expected, the Redmi Note 14 Pro Plus heads up the Redmi Note 14 series alongside theRedmi Note 14and Redmi Note 14 Pro. Li

Oppo Find X8 design looks like a cross between Apple iPhone 16 Pro and OnePlus Open in early images Oppo Find X8 design looks like a cross between Apple iPhone 16 Pro and OnePlus Open in early images Sep 28, 2024 am 06:04 AM

Historically, Oppo has refreshed its flagship 'Find X' series in late winter or early spring, save for the original Find X that it announced in June 2018. To that end, the Find X7 and Find X7 Ultra are barely more than six months old at this point. H

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Lenovo reveals new color option for the 2024 Legion Y700 gaming tablet Lenovo reveals new color option for the 2024 Legion Y700 gaming tablet Sep 29, 2024 am 06:05 AM

Lenovo is gearing up to launch the 2024 Legion Y700 on September 29 in China. This new Android gaming tablet will be going against the RedMagic Nova, and the company has already confirmed almost all the specs of the device. Now, hours before the full

Samsung Galaxy Z Fold Special Edition revealed to land in late October as conflicting name emerges Samsung Galaxy Z Fold Special Edition revealed to land in late October as conflicting name emerges Oct 01, 2024 am 06:21 AM

The launch of Samsung's long-awaited 'Special Edition' foldable has taken another twist. In recent weeks, rumours about the so-called Galaxy Z Fold Special Edition went rather quiet. Instead, the focus has shifted to the Galaxy S25 series, including

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles