Cocos2d-js和Android交互

摘要:
说白了,JavaScript和Java之间的函数是相互调用的。让我们来看看这种交互的效果,以便为未来的SDK做准备。要点:javascript调用java:jsb。反射callStaticMethod;Java调用javascript:Cocos2dxJavascriptJavaBridge.evalString//Javatojs在这里,我粘贴了应用程序的代码。js和AppActivity。java的Android项目。代码也有注释。它是纯干的,如果你把它拿走,你可以用它!

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

先看一下效果

Cocos2d-js和Android交互第1张

有了这个交互,为了以后接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.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 android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.WindowManager;
import android.widget.Toast;


import org.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 extends Cocos2dxActivity{
    
    /*
     * by joe
     */
    private static AppActivity app = null;
    //private static Context mContent = null;
    
    static String hostIPAdress = "0.0.0.0";
    @Override
    protected void onCreate(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;
    }
    
    @Override
    public Cocos2dxGLSurfaceView onCreateView() {
        Cocos2dxGLSurfaceView glSurfaceView = new Cocos2dxGLSurfaceView(this);
        // TestCpp should create stencil buffer
        glSurfaceView.setEGLConfigChooser(5, 6, 5, 0, 16, 8);

        return glSurfaceView;
    }

    public String 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 static String getLocalIpAddress() {
        return hostIPAdress;
    }
    
    private static native boolean nativeIsLandScape();
    private static native boolean nativeIsDebug();
    
    
    //---------------以下是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
     * 测试无返回值的
     * @param msg
     */
    public static void hello(final String msg){  
        System.out.println(msg);  
        
        app.runOnUiThread(new Runnable() {
            
            @Override
            public void run() {
            
                Toast.makeText(app, msg, Toast.LENGTH_SHORT).show();
            }
        });

    }  
    
    /**
     * 
     * var result = jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity", "sum", "(II)I", 3, 7);
     * js->java
     * 测试有返回值的
     * @param a
     * @param b
     * @return
     */
    public static int sum(int a, int b){
        return a + b;
    }
    
    
    /**
     * 弹出一个对话框
     * @param title
     * @param message
     */
    public static  void showAlertDialog(final String title,final String message) {

        //这里一定要使用runOnUiThread
        app.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // 创建构建器
                AlertDialog.Builder builder = new AlertDialog.Builder(app);
                builder.setTitle(title)//提示
                .setMessage(message)//您确认要退出游戏?
                .setIcon(null)//.setIcon(R.drawable.icon)
                .setPositiveButton("确定", new DialogInterface.OnClickListener(){

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        //System.out.println("是 clicked");
                        Toast.makeText(app, "确定", Toast.LENGTH_SHORT).show();
                        
                        //跳出一个提示。
                        //Toast.makeText(mContent, "确定", Toast.LENGTH_SHORT).show();
                        
                        //call cocos 函数 exit_sure
                        app.runOnGLThread(new Runnable() {  
                            @Override  
                            public void run() {  
                                Cocos2dxJavascriptJavaBridge.evalString("Global.mlayer.exit_sure();"); // java to js  
                            }  
                        });
                        
                    }})
                .setNegativeButton("取消", new DialogInterface.OnClickListener(){

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        //System.out.println("否 clicked");
                        Toast.makeText(app, "取消", Toast.LENGTH_SHORT).show();
                        
                        //call cocos 函数 exit_cancle
                        app.runOnGLThread(new Runnable() {  
                            @Override  
                            public void run() {  
                                Cocos2dxJavascriptJavaBridge.evalString("Global.mlayer.exit_cancle();"); // java to js  
                            }  
                        });
                        
                    }});
                builder.create().show();  
            }
        });
    }
         
    /**
     * java->js
     * @param a
     * @param b
     */
    public static void callcocos(int a){  

         app.runOnGLThread(new Runnable() {  
            @Override  
            public void run() {  
                //test
               // Cocos2dxJavascriptJavaBridge.evalString("SDKManage.javaToJSCall("a", 5 , 7);"); // java to js  
            }  
        });
             
    }  
    
}

免责声明:文章转载自《Cocos2d-js和Android交互》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇matplotlib入门转《trackingjs人脸检测》下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

Deno会在短期内取代Node吗?

转载请注明出处:葡萄城官网,葡萄城为开发者提供专业的开发工具、解决方案和服务,赋能开发者。 原文出处:https://blog.bitsrc.io/what-is-deno-and-will-it-replace-nodejs-a13aa1734a74   Deno是什么? Deno v1.0.0已于5月13日正式发布。 其开发者为Ryan Dahl...

网站开发常用技巧收集(防复制,防另存等等)

1. 将彻底屏蔽鼠标右键 oncontextmenu="window.event.returnValue=false" 用于Table <table border oncontextmenu=return(false)><td>no</table> 2. 取消选取、防止复制 <body onselectstar...

C#: 通过html调用WinForm 。。。。。

完整测试代码:Form1.cs 代码 using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;n...

JavaScript实现简单进度条

      好久没更新博客了,换了工作环境,比较忙,月底了一篇文章都没有更新。这里简单实现一个功能。Javascript实习进度条。文本借鉴于:http://blog.csdn.net/2004v2004/archive/2008/02/19/2106689.aspx,在次基础上通过Javascript来实现这个功能。欢迎提出意见。 可以通过...

【转】Unobtrusive Ajax的使用

【转】Unobtrusive Ajax的使用 Ajax (Asynchronous JavaScript and XML 的缩写),如我们所见,这个概念的重点已经不再是XML部分,而是 Asynchronous 部分,它是在后台从服务器请求数据的一种模型。MVC 框架内置了对 Unobtrusive Ajax 的支持,它允许我们通过 MVC 的 He...

IE下javascript获取文件大小

客户端用javascript获取文件大小 实现代码如下: <script type="text/javascript" language="javascript">    function getFileSize(fileName)    {        if(document.all)//判断是否是IE浏览器       {      ...