Cocos2d-js和Android交互

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

先看一下效果

有了这个交互,为了以后接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
            }
        });

    }  

}
时间: 2024-12-09 02:44:49

Cocos2d-js和Android交互的相关文章

js和android交互

如何提示alert webview.setWebChromeClient(new WebChromeClient() { @Override public boolean onJsAlert(WebView view, String url, String message, final JsResult resulta) { AlertDialog.Builder b2 = new AlertDialog.Builder(MainActivity.this) .setTitle("标题"

android 与JS之间的交互

在页面布局很复杂并且是动态的时候,android本身的控件就变得不是那么地灵活了,只有借助于网页的强大布局能力才能实现,但是在操作html页面的同时也需要与android其它的组件存在交互,比如说 在load一个url时, 用户点击页面内的某个按钮后, 页面调用android内的组件函数或由android组件去调用JS代码去更新页面,这都是交互问题,听起来很复杂,其实不用担心,webview这个类已经帮我们实现了,只需要直接用就好了. webview用法1 1.在要Activity中实例化Web

js 与 ios Android交互

一.android 交互 1.js调用webview 在android API Level 17及以上的版本中,就会出现js调用不了android的代码,这是版本兼容的问题,需要在调用的方法上面加一个注解:@JavascriptInterface,这个注解需要导入一个包:import android.webkit.JavascriptInterface; public void onCreate(Bundle savedInstanceState) { //给js设置调用的方法 this.app

cocos2d jsb 打包 Android APK

1.首先要会普通的cpp 打包成Android APK 以下所说的是在cocos2d-x 2.2.2 或者 2.3 版本中.本文在Eclipse总用ndk编译cocos2d-x. 老生常谈cocos2d-x JSB不是简单的js代码,涉及到C++代码,如果是Android的话又涉及到Java代码,有点复杂,如果搞过Android下的Jni的话会熟悉些.可以看下这篇文章:<Android Jni 例子 Hello JNI,ndk> Android为了提高开发者开发应用的速度,降低难度,选择了Ja

WebView中JS调用Android Method 遇到的坑整理

WebView是android中常用的一个组件,其作用是展示网页,并让网页和android app进行一些业务逻辑上的交互. 其坑无数,相信用过的都知道,一个一个来解决吧. 1.怎么互调: <!DOCTYPE> <html> <head> <meta charset="UTF-8"> <script type="text/javascript"> function android(bl){ if(bl){

cocos2d js ClippingNode 制作标题闪亮特效

1.效果图: 之前在<Android 高仿 IOS7 IPhone 解锁 Slide To Unlock>中制作了文字上闪亮移动的效果,这次我们来看下怎样在cocos2d js 中做出类似的效果. 顺便给我公司的游戏打下广告.https://itunes.apple.com/cn/app/kuang-zhan-san-guo/id691116157? mt=8 2.效果原理 很easy.就是一张白色两边羽化的图片在标题上从左往右移动.可是普通的移动会穿帮.我们须要以标题作为模板来截取白色的图片

WebView之js调用Android类的方法传递数据

1,具体的思路如下: 在android中写一个Activity,里面写一个webview,这个webview加载本地的一个html文件,显示这个网页,这个网页包括一个用户名和密码的输入框和两个按钮(只有登陆按钮有用),输入用户名密码之后调用android中的类,并把输入的数据传过去,再在android中输出出来(具体你那数据做什么操作就看你的需求了),这样就做大额js与android数据交互的效果了: 在android端,一些webviwe的设置和自定义类的写法如下源码: package com

iOS 开发之JS与Native交互

最近项目中用到了JS与OC交互的,所以我就来讲一下JS与OC交互的详细过程,以及在做项目的时候遇到的问题,跟大家分享一下. 1:关于交互实现方式的选择. 网上讨论比较多的有一个第三方库WebViewJavascriptBridge,个人不建议用,因为本身我们在做H5交互的时候就是给前端增加了工作量,而这种处理方式就需要前端要配置两套代码,一套给安卓,一套给iOS,而且不利于调试.所以我最后选择用系统的JavaScriptCore框架,JavaScriptzCore内部有五个框架,分别是: #im

UIWebView与JS的深度交互

事情的起因还是因为项目需求驱动.折腾了两天,由于之前没有UIWebView与JS交互的经历,并且觉得这次在功能上有一定的创造性,特此留下一点文字,方便日后回顾. 我要实现这样一个需求:按照本地的CSS文件展示一串网络获取的带HTML格式的只有body部分的文本,需要自己拼写完整的HTML.除此之外,还需要禁用获取的HTML文本中自带的 < img > 标签自动加载,并把下载图片的操作放在native端来处理,并通过JS将图片在Cache中的地址返回给UIWebview. 之所以要把图片操作放在