coco2dx java交互_Cocos2d-js和Android交互

说白了,就是JavaScript和Java之间的函数互相调用。

先看一下效果

51f0732b6731d0f6c6f337f57e7aea4d.gif

有了这个交互,为了以后接sdk做准备。

要点:

javascript调用java:

jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity", "hello", "(Ljava/lang/String;)V", "this is a message from js");

java调用javaScript:

Cocos2dxJavascriptJavaBridge.evalString("Global.mlayer.exit_cancle();"); // java to js

在这里我把这cocos2d-js的app.js  和 Android工程的AppActivity.java 的代码贴上,代码也有注释,纯干货,拿走就能用!

app.js:

var HelloWorldLayer = cc.Layer.extend({

txt_info:null,

sprite:null,

ctor:function ()

{

//

// 1. super init first

this._super();

/

// 2. add a menu item with "X" image, which is clicked to quit the program

// you may modify it.

// ask the window size

var size = cc.winSize;

var mainscene = ccs.load(res.MainScene_json);

this.addChild(mainscene.node);

/* you can create scene with following comment code instead of using csb file.

/

// 3. add your codes below...

// add a label shows "Hello World"

// create and initialize a label

var helloLabel = new cc.LabelTTF("Hello World", "Arial", 38);

// position the label on the center of the screen

helloLabel.x = size.width / 2;

helloLabel.y = size.height / 2 + 200;

// add the label as a child to this layer

this.addChild(helloLabel, 5);

// add "HelloWorld" splash screen"

this.sprite = new cc.Sprite(res.HelloWorld_png);

this.sprite.attr({

x: size.width / 2,

y: size.height / 2

});

this.addChild(this.sprite, 0);

*/

//“测试传参”按钮

var btn_hello = ccui.helper.seekWidgetByName(mainscene.node, "Button_1");

btn_hello.addTouchEventListener(this.btn_hello_clicked,this);

//"测试返回值" 按钮

var btn_testReturn = ccui.helper.seekWidgetByName(mainscene.node, "Button_2");

btn_testReturn.addTouchEventListener(this.btn_testReturn_clicked,this);

//“测试对话框” 按钮

var btn_dialog = ccui.helper.seekWidgetByName(mainscene.node, "Button_3");

btn_dialog.addTouchEventListener(this.btn_dialog_clicked,this);

//文本提示

this.txt_info = ccui.helper.seekWidgetByName(mainscene.node, "Text_1");

this.txt_info.setString("default");

return true;

},

//打开java层的对话框

btn_dialog_clicked:function(sender,type)

{

if(type == ccui.Widget.TOUCH_ENDED)

{

//弹出提示框 ok

jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity", "showAlertDialog", "(Ljava/lang/String;Ljava/lang/String;)V", "提示","您确认要退出游戏?");

}

},

//测试 java函数的返回值

btn_testReturn_clicked:function(sender,type)

{

if(type == ccui.Widget.TOUCH_ENDED)

{

//测试返回值 ok

var result = jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity", "sum", "(II)I", 3, 7);

cc.log("result"+result);

this.txt_info.setString("sum="+result);

}

},

btn_hello_clicked:function(sender,type){

//根据触发事件的类型进行分情况处理

switch (type)

{

case ccui.Widget.TOUCH_BEGAN:

//cc.log("btn_hello Touch Began");

break;

case ccui.Widget.TOUCH_MOVED:

//cc.log("btn_hello Touch Moved");

break;

case ccui.Widget.TOUCH_ENDED:

//cc.log("btn_hello Touch Ended");

cc.log("TODO call java");

jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity", "hello", "(Ljava/lang/String;)V", "this is a message from js");

break;

case ccui.Widget.TOUCH_CANCELED:

//cc.log("btn_hello Touch Canceled");

break;

default:

break;

}

},

exit_sure:function()

{

this.txt_info.setString("确定");

},

exit_cancle:function()

{

this.txt_info.setString("取消");

},

});

var HelloWorldScene = cc.Scene.extend({

onEnter:function () {

this._super();

var layer = new HelloWorldLayer();

Global.mlayer = layer;//保存到全局变量

this.addChild(layer);

}

});

AppActivity.java:

/****************************************************************************

Copyright (c) 2008-2010 Ricardo Quesada

Copyright (c) 2010-2012 cocos2d-x.org

Copyright (c) 2011 Zynga Inc.

Copyright (c) 2013-2014 Chukong Technologies Inc.http://www.cocos2d-x.orgPermission 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.

****************************************************************************/

packageorg.cocos2dx.javascript;importorg.cocos2dx.lib.Cocos2dxActivity;importorg.cocos2dx.lib.Cocos2dxGLSurfaceView;importandroid.app.AlertDialog;importandroid.content.Context;importandroid.content.DialogInterface;importandroid.content.pm.ActivityInfo;importandroid.net.wifi.WifiInfo;importandroid.net.wifi.WifiManager;importandroid.os.Bundle;importandroid.view.WindowManager;importandroid.widget.Toast;importorg.cocos2dx.lib.Cocos2dxJavascriptJavaBridge;//The name of .so is specified in AndroidMenifest.xml. NativityActivity will load it automatically for you.//You can use "System.loadLibrary()" to load other .so files.

public class AppActivity extendsCocos2dxActivity{/** by joe*/

private static AppActivity app = null;//private static Context mContent = null;

static String hostIPAdress = "0.0.0.0";

@Overrideprotected voidonCreate(Bundle savedInstanceState) {//TODO Auto-generated method stub

super.onCreate(savedInstanceState);if(nativeIsLandScape()) {

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);

}else{

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);

}if(nativeIsDebug()){

getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

}

hostIPAdress=getHostIpAddress();/*** by joe*/app= this;//mContent = this;

}

@OverridepublicCocos2dxGLSurfaceView onCreateView() {

Cocos2dxGLSurfaceView glSurfaceView= new Cocos2dxGLSurfaceView(this);//TestCpp should create stencil buffer

glSurfaceView.setEGLConfigChooser(5, 6, 5, 0, 16, 8);returnglSurfaceView;

}publicString getHostIpAddress() {

WifiManager wifiMgr=(WifiManager) getSystemService(WIFI_SERVICE);

WifiInfo wifiInfo=wifiMgr.getConnectionInfo();int ip =wifiInfo.getIpAddress();return ((ip & 0xFF) + "." + ((ip >>>= 8) & 0xFF) + "." + ((ip >>>= 8) & 0xFF) + "." + ((ip >>>= 8) & 0xFF));

}public staticString getLocalIpAddress() {returnhostIPAdress;

}private static native booleannativeIsLandScape();private static native booleannativeIsDebug();//---------------以下是cocos2dx-js 与 java 交互--------------------------

/** 目前Cocos2d-js中支持的Java类型签名有下面4种

Java类型 签名

int I

float F

boolean Z

String Ljava/lang/String;*/

/***

* jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity", "hello", "(Ljava/lang/String;)V", "this is a message from js");

* js->java

* 测试无返回值的

*@parammsg*/

public static void hello(finalString msg){

System.out.println(msg);

app.runOnUiThread(newRunnable() {

@Overridepublic voidrun() {

Toast.makeText(app, msg, Toast.LENGTH_SHORT).show();

}

});

}/***

* var result = jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity", "sum", "(II)I", 3, 7);

* js->java

* 测试有返回值的

*@parama

*@paramb

*@return

*/

public static int sum(int a, intb){return a +b;

}/*** 弹出一个对话框

*@paramtitle

*@parammessage*/

public static void showAlertDialog(final String title,finalString message) {//这里一定要使用runOnUiThread

app.runOnUiThread(newRunnable() {

@Overridepublic voidrun() {//创建构建器

AlertDialog.Builder builder = newAlertDialog.Builder(app);

builder.setTitle(title)//提示

.setMessage(message)//您确认要退出游戏?

.setIcon(null)//.setIcon(R.drawable.icon)

.setPositiveButton("确定", newDialogInterface.OnClickListener(){

@Overridepublic void onClick(DialogInterface dialog, intwhich) {//System.out.println("是 clicked");

Toast.makeText(app, "确定", Toast.LENGTH_SHORT).show();//跳出一个提示。//Toast.makeText(mContent, "确定", Toast.LENGTH_SHORT).show();//call cocos 函数 exit_sure

app.runOnGLThread(newRunnable() {

@Overridepublic voidrun() {

Cocos2dxJavascriptJavaBridge.evalString("Global.mlayer.exit_sure();"); //java to js

}

});

}})

.setNegativeButton("取消", newDialogInterface.OnClickListener(){

@Overridepublic void onClick(DialogInterface dialog, intwhich) {//System.out.println("否 clicked");

Toast.makeText(app, "取消", Toast.LENGTH_SHORT).show();//call cocos 函数 exit_cancle

app.runOnGLThread(newRunnable() {

@Overridepublic voidrun() {

Cocos2dxJavascriptJavaBridge.evalString("Global.mlayer.exit_cancle();"); //java to js

}

});

}});

builder.create().show();

}

});

}/*** java->js

*@parama

*@paramb*/

public static void callcocos(inta){

app.runOnGLThread(newRunnable() {

@Overridepublic voidrun() {//test//Cocos2dxJavascriptJavaBridge.evalString("SDKManage.javaToJSCall(\"a\", 5 , 7);");//java to js

}

});

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Cocos2d是一种流行的2D游戏引擎,它支持多平台开发,包括iOS、Android、Windows、Mac OS X等。Cocos2d-python是Cocos2d-x游戏引擎的Python版本,它提供了许多强大的功能,如游戏场景、动画、精灵、物理引擎等,非常适合开发2D游戏。 下面是一个简单的Cocos2d-python的helloworld程序: 1. 安装Cocos2d-python 在安装Cocos2d-python之前,需要先安装Python和pip。然后使用pip命令安装Cocos2d-python: ``` pip install cocos2d ``` 2. 创建一个新的Cocos2d-python项目 打开命令行窗口,进入到要创建项目的目录,然后执行以下命令: ``` cocos new mygame -p com.mycompany.mygame -l python ``` 其中,mygame是项目名称,com.mycompany.mygame是包名。 3. 编写helloworld程序 在mygame项目的src目录下创建一个新的Python文件helloworld.py,然后输入以下代码: ```python import cocos class HelloWorld(cocos.layer.Layer): def __init__(self): super(HelloWorld, self).__init__() label = cocos.text.Label( 'Hello, world!', font_name='Times New Roman', font_size=32, anchor_x='center', anchor_y='center' ) label.position = 320, 240 self.add(label) if __name__ == '__main__': cocos.director.director.init() HelloWorldScene = cocos.scene.Scene(HelloWorld()) cocos.director.director.run(HelloWorldScene) ``` 这个程序创建了一个名为HelloWorld的Layer,该Layer包含一个居中显示的文本标签“Hello, world!”。最后,它创建了一个Scene,将HelloWorld添加到Scene中,并运行Scene。 4. 运行helloworld程序 在命令行窗口中进入mygame项目的根目录,然后执行以下命令: ``` python src/helloworld.py ``` 程序将会启动,并显示一个居中显示的“Hello, world!”文本标签。 这是一个简单的Cocos2d-python的helloworld程序,你可以在此基础上进一步学习Cocos2d-python的开发。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值