Cocos2d-js Reflex

Source: Internet
Author: User

How to invoke the Java method directly on the Android platform using JS

A new feature has been added to the Cocos2d-js 3.0beta, which allows us to invoke Java's static methods directly in JS via reflection on the Android platform. The way it's used is simple:

1 var o = Jsb.reflection.callStaticMethod (ClassName, MethodName, methodsignature, Parameters ...)

In the callStaticMethod method, we can call Java's static method directly by passing in Java's class name, method name, method signature, and can get the return value of Java method. The class name and method signature described below may be a little odd, but Java's specifications are the same.

Class name

The class name in the parameter must be the full class name that contains the Java package path, for example, we org.cocos2dx.javascript write a class under this package Test :

Package Org.cocos2dx.javascript;public class Test {    void  Hello (String msg) {        SYSTEM.OUT.PRINTLN (msg);    }     int sum (intint  b) {        return a + b;    }     int sum (int  a) {        return A + 2;    }}

So the full class name of the test class should be org/cocos2dx/javascript/Test , note that this must be a slash / , not the point we used to in Java code . .

Method name

The method name is simple, that is, the method's original name, such as the name of the sum method sum .

Method signature

The method signature is slightly more complex, and the simplest method signature is ()V that it represents a method that does not have a parameter that does not return a value. Some other examples:

    • (I)Vmeans that the parameter is an int and there is no return value
    • (I)Imeans that the parameter is an int and the return value is int
    • (IF)ZRepresents an int and a float for the parameter, and a method that returns a Boolean value

Now there's some understanding, the notation inside the parentheses represents the parameter type, and the symbol after the parentheses indicates the return value type. Because Java is allowed for function overloading, there can be several methods with the same method name but different parameter return values, which are used to help distinguish the methods of the same names.

The following 4 types of Java type signatures are currently supported in COCOS2D-JS:

Java Type Signature
Int I
Float F
Boolean Z
String ljava/lang/string;
Parameters

Parameters can be 0 or any number, directly using the JS Number,bool and string can be.

Using the example

We will invoke the static method in the test class above:

// Call the Hello method jsb.reflection.callStaticMethod ("Org/cocos2dx/javascript/test", "Hello", "(ljava/lang/string;) V "," This was a message from JS "); // call the first sum method var result = Jsb.reflection.callStaticMethod ("Org/cocos2dx/javascript/test", "Sum", "(II) I", 3, 7  // Ten // Call the second sum method var result = Jsb.reflection.callStaticMethod ("Org/cocos2dx/javascript/test", "Sum", "(i) I", 3  // 5

It's easy to have the right output on your console.

# #注意 Another thing to note is that in Android applications, the logic of Cocos rendering and JS is done in the GL thread, and the UI update for Android itself is done in the app's UI thread, So if the Java method that we call in JS has any action to refresh the UI, it needs to be done on the UI thread.

For example, in the following example we call a Java method, which pops up an Android Alert dialog box.

//give us a little bit of the familiar appactivity class .Public class Appactivity extends Cocos2dxactivity {private static appactivity app=NULL; @Override PublicvoidonCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); App= This; } public staticvoidShowalertdialog (Final string title,final string message) {//be sure to use runonuithread hereApp.runonuithread (NewRunnable () {@Override publicvoidrun () {Alertdialog Alertdialog=NewAlertdialog.builder (APP). Create ();                Alertdialog.settitle (title);                Alertdialog.setmessage (message);                Alertdialog.seticon (R.drawable.icon);            Alertdialog.show ();    }        }); }}

And then we call it in JS.

Jsb.reflection.callStaticMethod ("Org/cocos2dx/javascript/appactivity", "Showalertdialog", "(ljava/lang/string; ljava/lang/string;) V "," title "," Hahahahha ");

This calls you to see an Android Native Alert dialog box.

Add some more material.

Now that we can call Java from JS, can it be reversed? Of course! Include Cocos2dxjavascriptjavabridge in your project, this class has a evalString way to execute the JS code, which is located in the frameworks\js-bindings\bindings\manual\platform\android\java\src\org\cocos2dx\lib folder. We will add a button to the Alert dialog box and execute JS in its response. In contrast to the above scenario, this execution of the JS code must be done in the GL thread.

New Dialoginterface.onclicklistener () {    voidint  which) {        //  Be sure to execute        app.runonglthread (new  Runnable () {            @Override            void in the GL thread  Run () {                cocos2dxjavascriptjavabridge.evalstring ("Cc.log (\" Javascript Java bridge!\ ")") ;            }        });    }});

After clicking the OK button, you should be able to see the correct output in the console. Evalstring can execute any JS code, and it can access your object in the JS code.

How to invoke the OC method directly on the iOS platform using JS

In the Cocos2d-js v3.0 RC2, like on Android JS call Java, COCOS2D-JS also provides a way to call Objective-c on iOS and Mac directly, the sample code is as follows:

var ojb = Jsb.reflection.callStaticMethod (ClassName, Methodnmae, arg1, arg2, ...);

In the jsb.reflection.callStaticMethod method, we can directly call OC's static method by passing in the class name of OC, method name, parameter, and can get the return value of OC method.

Class
    • The class name in the parameter only needs to pass in the class name in OC, unlike Java, where the class name does not require a path. For example, if you create a new class under the project, NativeOcClass as long as you introduce him to the project, then his class name is NativeOcClass that you don't need to pass in its path.
    Import <Foundation/Foundation.h>    @interface nativeocclass:nsobject    + (BOOL) Callnativeuiwithtitle: (NSString *) title andcontent: (NSString *) content;    @end

Method
    • The JS to OC reflection only supports static methods of classes in OC.
    • Method name comparison It is important to note that we need to pass in the full method name, especially if a method has parameters, you need to take his : also. According to the above example. At this point the method name is callnativeuiwithtitle:andcontent:, do not miss out between them :.
    • If it is a function without parameters, then he does not need :, the following code, his method name is callNativeWithReturnString , because there is no parameter, he does not need :, and OC method of writing consistent.
+ (NSString *) callnativewithreturnstring;

Using the example
    • The following example code calls the above NativeOcClass method, which we only need to invoke in the JS layer:
    var ret = Jsb.reflection.callStaticMethod ("Nativeocclass",                                                "Callnativeuiwithtitle: Andcontent: ",                                                " Cocos2d-js ",                                                " yes! a Native UI from Reflection ");

    • Here is the implementation of this method in OC, which can be seen to pop up a native dialog box. and title content set it to the parameter you passed in, and return a Boolean return value.
    + (BOOL) Callnativeuiwithtitle: (NSString *) title andcontent: (NSString *) content{        *alertview = [[ Uialertview alloc] initwithtitle:title message:content delegate:self cancelbuttontitle:@ "Cancel" otherButtonTitles:@ "OK", nil];        [Alertview show];         return true ;    }

    • At this point, you can ret accept the return value (TRUE) returned from OC in.
Attention

In the OC implementation, if the parameters of the method need to use float, int, bool, use the following types to convert:

float,int use nsnumber type bool please use BOOL type. For example, the following code, we pass in 2 floating-point numbers, and then calculate their merge return, we use nsnumber instead of int, float to go as the parameter type. 

+ (float) Addtwonumber: (NSNumber *) NUM1 and: (NSNumber *) num2{    float result = [NUM1 floatvalue]+[num2 floatvalue];     return result;}

The current parameters and return values support int, float, bool, string, and the remaining types are temporarily unsupported.

File directory

Java:frameworks\runtime-src\proj.android\src\org\cocos2dx\javascript

Ios:frameworks\runtime-src\proj.ios_mac\mac

Cocos2d-js Reflex

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.