【原】cocos2d-x游戏开发之C++调用Java代码

通过JNI调用
准备工作:
首先用VS工程导入$cocos2d_Root\cocos2dx\platform\android\jni\JniHelper.h
接着导入$Java\jdk1.6.0_10\include\jni.h
再导入$Java\jdk1.6.0_10\include\win32\jni_md.h
C++层代码
通过JNI调用
准备工作:
首先用VS工程导入$cocos2d_Root\cocos2dx\platform\android\jni\JniHelper.h
接着导入$Java\jdk1.6.0_10\include\jni.h
再导入$Java\jdk1.6.0_10\include\win32\jni_md.h
C++层代码
在点击事件中添加如下代码

#if(CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)//条件编译语句

        {

                const char *message = "Hello";//需要传递到Java层的字符串

                JniMethodInfo methodInfo;

                bool isHave = JniHelper::getStaticMethodInfo(methodInfo,

                        "com/kengdie/test/Test",//需要调用的Java文件

                        "showMessageFromNative",//调用的方法名

                        "(Ljava/lang/String;)V");//参数

                if(isHave){

                        CCLog("the showMessage method is exits");

                        jstring StringArg = methodInfo.env->NewStringUTF(message);

                        methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, StringArg);

                }else{

                        CCLog("the showMessage method is not exits");

                }

        }

#endif

Java层代码

public class Test extends Cocos2dxActivity{

        ......

        private static LinkUp context;

        ......

        protected void onCreate(Bundle savedInstanceState){

                ......

                context = this;

                ......

        }

        public static void showMessageFromNative(String message){                    Message msg = new Message();

                   msg.what = 1;

                    msg.obj = message;

                    handler.sendMessage(msg);

        }

        static Handler handler = new Handler(){

                    @Override

                public void handleMessage(android.os.Message msg) {

                     switch (msg.what) {

                        case 1:

                                String message = (String) msg.obj;

                                Toast.makeText(context, message, Toast.LENGTH_SHORT).show();

                                break;

                        default:

                                break;

                        }

             };

     };

}

注:C++代码需要保存为UTF-8

你可能感兴趣的:(cocos2d-x)