How to Call Java methods using JavaScript on Android

This document is based on v2.x. It may change slightly with Cocos Creator 3.0 and will be updated as soon as possible.

With the Cocos Creator Android build, developers can call Java static methods directly in JavaScript. Doing so is very simple:

  1. var result = jsb.reflection.callStaticMethod(className, methodName, methodSignature, parameters...)

In callStaticMethod method, pass the Java class name, method name, method signature with parameters, and get the return value from Java. The Java class name and method signature may be a little strange without having experience with JNI, but that is the Java specification.

Class name

The class name must contain Java package path. For example, if a class, Test, exists in the package org.cocos2dx.javascript:

  1. package org.cocos2dx.javascript;
  2. public class Test {
  3. public static void hello(String msg) {
  4. System.out.println(msg);
  5. }
  6. public static int sum(int a, int b) {
  7. return a + b;
  8. }
  9. public static int sum(int a) {
  10. return a + 2;
  11. }
  12. }

The correct class name of Test is org/cocos2dx/javascript/Test. Please note that using a slash / is required, NOT using a dot ..

Method name

The method name is very simple. For example, the method names of the above two sum methods are both sum.

Method signature

The method signature is a little complex. The simplest signature is ()V, it represents a method which has no parameters and no return value. Examples:

  • (I)V represents a method which has a int parameter and no return value.
  • (I)I represents a method which has a int parameter and a int return value.
  • (IF)Z represents a method which has a int parameter and a float parameter, and returns boolean.

The symbols in brackets represent the type of parameters, and the symbol after bracket represent the type of return value. Because methods are allowed to be overloaded in Java, there can be multiple methods which hava the same method name, but different parameters and return value. The method signature is used to help identifying these methods.

Currently, Cocos Creator supports four Java types:

Java typesignature
intI
floatF
booleanZ
StringLjava / lang / String;

Parameters

The number of parameters can be 0 or more than one. And when we use callStaticMethod, we can use number, boolean and string of JavaScript directly.

Usage

Here is an example of invoking the static methods of Test class:

  1. //call hello method
  2. jsb.reflection.callStaticMethod("org/cocos2dx/javascript/Test", "hello", "(Ljava/lang/String;)V", "this is a message from JavaScript");
  3. //call the first sum method
  4. var result = jsb.reflection.callStaticMethod("org/cocos2dx/javascript/Test", "sum", "(II)I", 3, 7);
  5. cc.log(result); //10
  6. //call the second sum method
  7. var result = jsb.reflection.callStaticMethod("org/cocos2dx/javascript/Test", "sum", "(I)I", 3);
  8. cc.log(result); //5

Take a look on the Console, there should be correct output.

Attention

A very important thing that must be paid attention to is thread safety! With a Cocos Creator Android app, the engine and JavaScript VM works in the gl thread, and Android update its UI in the ui thread. If a Java method is called which will update the app UI, it must run in ui thread.

For example, calling a Java method which shows an Android AlertDialog:

  1. //make some modification in AppActivity class
  2. public class AppActivity extends Cocos2dxActivity {
  3. private static AppActivity app = null;
  4. @Override
  5. public void onCreate(Bundle savedInstanceState) {
  6. super.onCreate(savedInstanceState);
  7. app = this;
  8. }
  9. public static void showAlertDialog(final String title,final String message) {
  10. //we must use runOnUiThread here
  11. app.runOnUiThread(new Runnable() {
  12. @Override
  13. public void run() {
  14. AlertDialog alertDialog = new AlertDialog.Builder(app).create();
  15. alertDialog.setTitle(title);
  16. alertDialog.setMessage(message);
  17. alertDialog.setIcon(R.drawable.icon);
  18. alertDialog.show();
  19. }
  20. });
  21. }
  22. }

Next, calling showAlertDialog in JavaScript:

  1. jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity", "showAlertDialog", "(Ljava/lang/String;Ljava/lang/String;)V", "title", "hahahahha");

An Android native AlertDialog should show now.

One more thing

Now that it is possible to successfully called Java methods in JavaScript, is it possible to call JavaScript in Java? Of course!

The engine contains class CocosJavascriptJavaBridge, which has an evalString method that can execute JavaScript, and is located in the resources\3d\cocos2d-x-lite\cocos\platform\android\java\src\com\cocos\lib\CocosJavascriptJavaBridge.java file in the engine directory. Please note that this time JavaScript code should be run in the gl thread.

Consider an example of adding an OK button for the AlertDialog, and using evalString in its OnClickListener:

  1. alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
  2. public void onClick(DialogInterface dialog, int which) {
  3. // We must use runOnGLThread here
  4. app.runOnGLThread(new Runnable() {
  5. @Override
  6. public void run() {
  7. CocosJavascriptJavaBridge.evalString("cc.log(\"JavaScript Java bridge!\")");
  8. }
  9. });
  10. }
  11. });

Note: the engine does not promise security in multi-threaded currently, avoid JavaScript code being called in other threads during development to avoid various memory errors.

To call evalString in C++, please refer to the following method to ensure that evalString is executed in the thread where the JavaScript engine is:

  1. Application::getInstance()->getScheduler()->performFunctionInCocosThread([=](){
  2. se::ScriptEngine::getInstance()->evalString(script.c_str());
  3. });

After clicking OK button, notice the output. evalString can run any JavaScript code, and can access JavaScript variables.