前言
前2章 讲述了 android 调用 c++ so库,这章主要讲在android cocoscreator 中java 与js 相互调用;
1 准备
win7 64
androidstudio4.1.1 cocoscreator2.4.4
2 创建工程并修改
1> cocoscreator 创建个 helloworld 工程
2 > UI 界面如下
3> 增加个JavaCallJs.js
代码如下
const JavaCallJs = {
getVau: function (datastr) {
if (cc.game) {
cc.game.labelstr = datastr;
}
}
}
module.exports = JavaCallJs;
4 > 修改HelloWord.js 如下
const JavaCallJs = require("JavaCallJs");
cc.Class({
extends: cc.Component,
properties: {
label: {
default: null,
type: cc.Label
},
// defaults, set visually when attaching this script to the Canvas
text: 'Hello, World!',
inputfun:{
default:null,
type:cc.EditBox
},
inputparam:{
default:null,
type:cc.EditBox
},
inputrealparamcount:{
default:null,
type:cc.EditBox
},
inputrealparams:{
default:null,
type:cc.EditBox
},
button:{
default:null,
type:cc.Button
},
output:cc.Label
},
// use this for initialization
onLoad: function () {
this.label.string = this.text;
},
start:function(){
if (cc.sys.isNative && jsb != null && jsb != "undefined") {
this.output.string ="jsb function is vaild";
}else{
this.outputlog("jsb function is invaild");
}
if (!cc.game) {
cc.game = {};
cc.game.JavaCallJs = JavaCallJs;
this.outputlog("cc.game.JavaCallJs set[1]");
}else if (!cc.game.JavaCallJs){
cc.game.JavaCallJs = JavaCallJs;
this.outputlog("cc.game.JavaCallJs set[2]");
}
},
// called every frame
update: function (dt) {
},
//日志输出
outputlog:function(){//可变参数 arguments
if(cc.sys.isNative && cc.sys.platform == cc.sys.OS_ANDROID){
const cAppActivity = "org/cocos2dx/javascript/AppActivity";
let strlog="";
for (var i=0; i<arguments.length; i++) {
strlog = strlog + arguments[i];
}
jsb.reflection.callStaticMethod(cAppActivity,"systemoutput","(Ljava/lang/String;)V",strlog);
}else{
let strlog="";
for (var i=0; i<arguments.length; i++) {
strlog = strlog + arguments[i];
}
console.log(strlog);
}
},
showlable:function(str){
this.label.string = str ;
},
//
click:function(e){
this.showlable(e.target.name);
var self = this ;
switch(e.target.name){
case "button":
{
this.showlable("cc.sys.isNative="+cc.sys.isNative);
this.outputlog("cc.sys.isNative=",cc.sys.isNative,"cc.sys.platform=",cc.sys.platform,"cc.sys.ANDROID=",cc.sys.ANDROID);
if (cc.sys.isNative){
this.showlable("cc.sys.platform === cc.sys.ANDROID"+(cc.sys.platform === cc.sys.ANDROID));
// this.outputlog("cc.sys.isNative=",cc.sys.isNative,"cc.sys.platform=",cc.sys.platform,"cc.sys.ANDROID=",cc.sys.ANDROID);
if(cc.sys.platform === cc.sys.ANDROID){
let funstr = self.inputfun.string ;
let funparamstr = self.inputparam.string ;
let realcountstr = self.inputrealparamcount.string ;
let realparamstr = self.inputrealparams.string ;
funstr = funstr.trim(); //
funparamstr = funparamstr.trim(); //
realcountstr = realcountstr.trim(); //
realcountstr = realcountstr.toUpperCase() ; //大写
realparamstr = realparamstr.trim(); //
realparamstr = realparamstr.toUpperCase() ; //大写
this.outputlog("inputfun.string=",funstr, "inputparam.string=",funparamstr,"inputrealparamcount.string=",realcountstr, "inputrealparams.string=",realparamstr);
// var ojb = jsb.reflection.callStaticMethod(className, methodNmae, arg1, arg2, .....);
let params = funparamstr ;
let pos1 = params.indexOf("(");
let pos2 = params.indexOf(")");
this.outputlog("pos1=",pos1,"pos2",pos2,"params.length=",params.length);
if(params.length > pos2 && pos1 < pos2){
let rtnpm = params.substring(pos2);
rtnpm = rtnpm.trim(); //
//trim() 方法用于删除字符串的头尾空白符,空白符包括:空格、制表符 tab、换行符等其他空白符等。
//trim() 方法不会改变原始字符串。
//trim() 方法不适用于 null, undefined, Number 类型
// jsb.reflection.callStaticMethod("org/cocos2dx/lib/Cocos2dxActivity", "getDeviceID", "()Ljava/lang/String;");
//Number()
//this.showlable("111");
var realinput = [];
if(self.inputrealparamcount.string.length > 0 && self.inputrealparams.string.length > 0){
let ss1 = realcountstr.split("|"); //字符串数组
let ss2 = realparamstr.split("|"); //字符串数组
this.outputlog("ss1.length=",ss1.length,"ss2.length=",ss2.length);
if(ss1.length == ss2.length){
for (let i=0;i<ss1.length;i++){
switch(ss1[i]){
case "N": //Number
realinput.push(Number(ss2[i]));
break;
case "S": //string
realinput.push(ss2[i]);
break;
}
}
}
}
this.showlable("realinput.length="+realinput.length);
this.outputlog("realinput.length=",realinput.length,"realinput=",realinput.join("|"));
if(realinput.length > 0){
this.outputlog("realinput fun0",""+realinput[0]);
}
let outputstr = "";
const cAppActivity = "org/cocos2dx/javascript/AppActivity";
if(rtnpm.indexOf("V") >= 0){
//无返回参数
this.outputlog("rtnpm",rtnpm,"无参数返回");
switch(realinput.length){
case 0: jsb.reflection.callStaticMethod(cAppActivity,funstr,funparamstr); break;
case 1: jsb.reflection.callStaticMethod(cAppActivity,funstr,funparamstr,realinput[0]); break;
case 2: jsb.reflection.callStaticMethod(cAppActivity,funstr,funparamstr,realinput[0],realinput[1]); break;
case 3: jsb.reflection.callStaticMethod(cAppActivity,funstr,funparamstr,realinput[0],realinput[1],realinput[2]); break;
case 4: jsb.reflection.callStaticMethod(cAppActivity,funstr,funparamstr,realinput[0],realinput[1],realinput[2],realinput[3]); break;
case 5: jsb.reflection.callStaticMethod(cAppActivity,funstr,funparamstr,realinput[0],realinput[1],realinput[2],realinput[3],realinput[4]); break;
default:
return ;
}
// jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity",inputfun.string,inputparam.string);
outputstr = "no return params";
}else{
//有返回参数
this.outputlog("rtnpm",rtnpm,"有参数返回");
let rtnv ;
switch(realinput.length){
case 0: rtnv=jsb.reflection.callStaticMethod(cAppActivity,funstr,funparamstr); break;
case 1: rtnv=jsb.reflection.callStaticMethod(cAppActivity,funstr,funparamstr,realinput[0]); break;
case 2: rtnv=jsb.reflection.callStaticMethod(cAppActivity,funstr,funparamstr,realinput[0],realinput[1]); break;
case 3: rtnv=jsb.reflection.callStaticMethod(cAppActivity,funstr,funparamstr,realinput[0],realinput[1],realinput[2]); break;
case 4: rtnv=jsb.reflection.callStaticMethod(cAppActivity,funstr,funparamstr,realinput[0],realinput[1],realinput[2],realinput[3]); break;
case 5: rtnv=jsb.reflection.callStaticMethod(cAppActivity,funstr,funparamstr,realinput[0],realinput[1],realinput[2],realinput[3],realinput[4]); break;
default:
return ;
}
this.outputlog("rtnpm",rtnpm,"有参数返回");
// let rtnv = jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity",inputfun.string,inputparam.string);
if(isNaN(rtnv)){ //不是数字
if(typeof(rtnv) == 'string'){ //字符串{
outputstr = rtnv ;
}else if(typeof(rtnv) == 'object'){
outputstr = JSON.stringify(rtnv) ; //将对象转为字符串
//JSON.parse(str); 符串转为对象
}else {
outputstr = "return params is error";
}
} else {//是数字
outputstr = ""+rtnv ;
}
}
//加上时间
let time = new Date();
self.output.string = time.toLocaleString() + " " + outputstr ;
}
}
}
}
break;
case "bjvcalljs":
self.showlable(cc.game.labelstr);
break;
}
}
///
});
/*
目前 Cocos Creator 中支持的 Java 类型签名有下面 4 种:
Java类型 签名
int I
float F
boolean Z
String Ljava/lang/String;
*/
3 编译
1> 构建工程
2> 用AndroidStudio 打开 jsb-default\frameworks\runtime-src\proj.android-studio
修改AppActivity.java
代码如下:
/****************************************************************************
Copyright (c) 2015-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.javascript;
import org.cocos2dx.lib.Cocos2dxActivity;
import org.cocos2dx.lib.Cocos2dxGLSurfaceView;
import org.cocos2dx.lib.Cocos2dxJavascriptJavaBridge;
import android.os.Bundle;
import android.content.Intent;
import android.content.res.Configuration;
import android.util.Log;
public class AppActivity extends Cocos2dxActivity {
private static AppActivity _app = null ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Workaround in
// https://stackoverflow.com/questions/16283079/re-launch-of-activity-on-home-button-but-only-the-first-time/16447508
if (!isTaskRoot()) {
// Android launched another instance of the root activity into an existing task
// so just quietly finish and go away, dropping the user back into the activity
// at the top of the stack (ie: the last state of this task)
// Don't need to finish it again since it's finished in super.onCreate .
return;
}
// DO OTHER INITIALIZATION BELOW
SDKWrapper.getInstance().init(this);
_app = this;
}
@Override
public Cocos2dxGLSurfaceView onCreateView() {
Cocos2dxGLSurfaceView glSurfaceView = new Cocos2dxGLSurfaceView(this);
// TestCpp should create stencil buffer
glSurfaceView.setEGLConfigChooser(5, 6, 5, 0, 16, 8);
SDKWrapper.getInstance().setGLSurfaceView(glSurfaceView, this);
return glSurfaceView;
}
@Override
protected void onResume() {
super.onResume();
SDKWrapper.getInstance().onResume();
}
@Override
protected void onPause() {
super.onPause();
SDKWrapper.getInstance().onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
// Workaround in https://stackoverflow.com/questions/16283079/re-launch-of-activity-on-home-button-but-only-the-first-time/16447508
if (!isTaskRoot()) {
return;
}
SDKWrapper.getInstance().onDestroy();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
SDKWrapper.getInstance().onActivityResult(requestCode, resultCode, data);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
SDKWrapper.getInstance().onNewIntent(intent);
}
@Override
protected void onRestart() {
super.onRestart();
SDKWrapper.getInstance().onRestart();
}
@Override
protected void onStop() {
super.onStop();
SDKWrapper.getInstance().onStop();
}
@Override
public void onBackPressed() {
SDKWrapper.getInstance().onBackPressed();
super.onBackPressed();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
SDKWrapper.getInstance().onConfigurationChanged(newConfig);
super.onConfigurationChanged(newConfig);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
SDKWrapper.getInstance().onRestoreInstanceState(savedInstanceState);
super.onRestoreInstanceState(savedInstanceState);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
SDKWrapper.getInstance().onSaveInstanceState(outState);
super.onSaveInstanceState(outState);
}
@Override
protected void onStart() {
SDKWrapper.getInstance().onStart();
super.onStart();
}
public static int testfun1(int a,int b){
return a+b;
}
public static void systemoutput(String strlog){
System.out.println(strlog);
Log.d("AppActivity", strlog);
}
public static void testfun2(int a){
// AppActivity.this.test();
_app.test(a);
}
public void test(final int a){
//activity必须是继承自Cocos2dxActivity或者实现Cocos2dxHelperListener接口
this.runOnGLThread(new Runnable() {
@Override
public void run(){
//函数多参数如下输入
//String params = String.format("cc.game.JavaCallJs.getVau(\"%s\",\"%s\",\"%s\");",param1,param2,param3);
//String params = "cc.game.JavaCallJs.getVau(\""+param1+"\",\""+param2+"\");" ;
String params = String.format("cc.game.JavaCallJs.getVau(\"%s\")",String.valueOf(a*2));
Cocos2dxJavascriptJavaBridge.evalString(params);
}
});
}
}
4 测试
1:js call java
点击OK,结果正确,调用成功
1 > java call js
2 > 点击OK, js call java call js (js调用java函数,java函数里由调用js函数)
3> 点击bjvcalljs 查看结果
String params = String.format("cc.game.JavaCallJs.getVau(\"%s\")",String.valueOf(a*2));
Cocos2dxJavascriptJavaBridge.evalString(params);
5 js 与 java 调用完成
工程代码如有需要后续再上传