Cocosd-x对Java进行调用的测试代码

来源:互联网 发布:制作授权书软件 编辑:程序博客网 时间:2024/04/29 23:32

原文转自 http://blog.csdn.net/stupidcodegenerator/article/details/8589613?userName=peigong_dh&userInfo=lJf%2FdZQt4QaoKL2KNtoZ72d1g5BD1EyTYKahykMLnhr%2BYsrhMsTEZQLMUOIKjUHRJ940%2BFGME%2BpPDfDvOgR%2BQ9EiUzPmmSqKBGoE0F1NVjHdLYsLolHB6FY6X6eVy1UHuyu2c7JUc5QcuFCWAmpxpw%3D%3D

目前计划是这样的, 首先, 在Java代码中写两个测试的函数,JniTestFunction_Static, JniTestFunction.

话说,在VIM还不熟练的时候使用VIM真的是降低效率思密达。VIM和Emacs还是得会一个,考虑到Stalllman的固执己见,我还是觉得VIM更体贴一些。


JniHelper.h中定义了一个结构体JniMethodInfo和一个类JniHelper. 代码如下:

[cpp] view plaincopy
  1. /**************************************************************************** 
  2. Copyright (c) 2010-2011 cocos2d-x.org 
  3.  
  4. http://www.cocos2d-x.org 
  5.  
  6. Permission is hereby granted, free of charge, to any person obtaining a copy 
  7. of this software and associated documentation files (the "Software"), to deal 
  8. in the Software without restriction, including without limitation the rights 
  9. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
  10. copies of the Software, and to permit persons to whom the Software is 
  11. furnished to do so, subject to the following conditions: 
  12.  
  13. The above copyright notice and this permission notice shall be included in 
  14. all copies or substantial portions of the Software. 
  15.  
  16. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
  17. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
  18. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
  19. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
  20. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
  21. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
  22. THE SOFTWARE. 
  23. ****************************************************************************/  
  24. #ifndef __ANDROID_JNI_HELPER_H__  
  25. #define __ANDROID_JNI_HELPER_H__  
  26.   
  27. #include <jni.h>  
  28. #include <string>  
  29. #include "platform/CCPlatformMacros.h"  
  30.   
  31. NS_CC_BEGIN  
  32.   
  33. typedef struct JniMethodInfo_  
  34. {  
  35.       
  36. //  The env pointer is a structure that contains the interface to the   
  37. //  JVM. It includes all of the functions necessary to interact with   
  38. //  the JVM and to work with Java objects. Example JNI functions are   
  39. //  converting native arrays to/from Java arrays, converting native   
  40. //  strings to/from Java strings, instantiating objects, throwing   
  41. //  exceptions, etc. Basically, anything that Java code can do can be   
  42. //  done using JNIEnv, albeit with considerably less ease.  
  43.       
  44. //  env指针是一个包含了JVM接口的指针。他包含了全部必要的用来和JVM进行通讯的函数。比如  
  45. //  将本地数组转换成Java数组,将本地字符串转换成Java字符串,实例化对象,抛出异常等等。  
  46. //  基本上,任何可以用Java代码实现的功能都可以通过JNIEnv实现,尽管实现的不是那么轻松。  
  47.       
  48. //  A JNI interface pointer (JNIEnv*) is passed as an argument for each   
  49. //  native function mapped to a Java method, allowing for interaction   
  50. //  with the JNI environment within the native method. This JNI   
  51. //  interface pointer can be stored, but remains valid only in the   
  52. //  current thread. Other threads must first call AttachCurrentThread()   
  53. //  to attach themselves to the VM and obtain a JNI interface pointer.   
  54. //  Once attached, a native thread works like a regular Java thread   
  55. //  running within a native method. The native thread remains attached   
  56. //  to the VM until it calls DetachCurrentThread() to detach itself.[4]  
  57.   
  58. //  JNI interface pointer (JNIEnv*) 在每一个对应于Java函数的Native函数中都作为  
  59. //  一个参数传入,这样做可以让JNI环境和Native函数进行沟通。这个JNI接口会被储存,但是  
  60. //  只有在当前线程中有效。其他的线程必须首先调用AttachCurrentThread()来将他们自己  
  61. //  附到VM上并且获取一个JNIEnv.一旦附属到VM上,一个Native线程就会像一个Java线程那样  
  62. //  运行。本地线程会保持附属直到调用DetachCurrentThread().  
  63.   
  64. //  参见 jni.h  
  65.     JNIEnv *    env;  
  66.     jclass      classID;  
  67.     jmethodID   methodID;  
  68. } JniMethodInfo;  
  69.   
  70. class CC_DLL JniHelper  
  71. {  
  72. public:  
  73.     static JavaVM* getJavaVM();  
  74.     static void setJavaVM(JavaVM *javaVM);  
  75.     static jclass getClassID(const char *className, JNIEnv *env=0);  
  76.     static bool getStaticMethodInfo(JniMethodInfo &methodinfo, const char *className, const char *methodName, const char *paramCode);  
  77.     static bool getMethodInfo(JniMethodInfo &methodinfo, const char *className, const char *methodName, const char *paramCode);  
  78.     static std::string jstring2string(jstring str);  
  79.   
  80. private:  
  81.     static JavaVM *m_psJavaVM;  
  82. };  
  83.   
  84. NS_CC_END  
  85.   
  86. #endif // __ANDROID_JNI_HELPER_H__  

现在我定义一个JniMethodInfo. 然后用getStaticMethodInfo来尝试获得Java里面的jniTestFunction_Static的函数信息

写道HelloWorldScene.cpp中

[cpp] view plaincopy
  1. #include "HelloWorldScene.h"  
  2. #include "SimpleAudioEngine.h"  
  3.   
  4. #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)  
  5. #include <jni.h>  
  6. #include "platform/android/jni/JniHelper.h"  
  7. #include <android/log.h>  
  8. #endif  
  9.   
  10. using namespace cocos2d;  
  11. using namespace CocosDenshion;  
  12.   
  13. CCScene* HelloWorld::scene()  
  14. {  
  15.     // 'scene' is an autorelease object  
  16.     CCScene *scene = CCScene::create();  
  17.       
  18.     // 'layer' is an autorelease object  
  19.     HelloWorld *layer = HelloWorld::create();  
  20.   
  21.     // add layer as a child to scene  
  22.     scene->addChild(layer);  
  23.   
  24.     // return the scene  
  25.     return scene;  
  26. }  
  27.   
  28. // on "init" you need to initialize your instance  
  29. bool HelloWorld::init()  
  30. {  
  31.     //////////////////////////////  
  32.     // 1. super init first  
  33.     if ( !CCLayer::init() )  
  34.     {  
  35.         return false;  
  36.     }  
  37.   
  38.     /////////////////////////////  
  39.     // 2. add a menu item with "X" image, which is clicked to quit the program  
  40.     //    you may modify it.  
  41.   
  42.     // add a "close" icon to exit the progress. it's an autorelease object  
  43.     CCMenuItemImage *pCloseItem = CCMenuItemImage::create(  
  44.                                         "CloseNormal.png",  
  45.                                         "CloseSelected.png",  
  46.                                         this,  
  47.                                         menu_selector(HelloWorld::menuCloseCallback) );  
  48.     pCloseItem->setPosition( ccp(CCDirector::sharedDirector()->getWinSize().width - 20, 20) );  
  49.   
  50.     // create menu, it's an autorelease object  
  51.     CCMenu* pMenu = CCMenu::create(pCloseItem, NULL);  
  52.     pMenu->setPosition( CCPointZero );  
  53.     this->addChild(pMenu, 1);  
  54.   
  55.     /////////////////////////////  
  56.     // 3. add your codes below...  
  57.   
  58.     // add a label shows "Hello World"  
  59.     // create and initialize a label  
  60.     CCLabelTTF* pLabel = CCLabelTTF::create("Hello World""Thonburi", 34);  
  61.   
  62.     // ask director the window size  
  63.     CCSize size = CCDirector::sharedDirector()->getWinSize();  
  64.   
  65.     // position the label on the center of the screen  
  66.     pLabel->setPosition( ccp(size.width / 2, size.height - 20) );  
  67.   
  68.     // add the label as a child to this layer  
  69.     this->addChild(pLabel, 1);  
  70.   
  71.     // add "HelloWorld" splash screen"  
  72.     CCSprite* pSprite = CCSprite::create("HelloWorld.png");  
  73.   
  74.     // position the sprite on the center of the screen  
  75.     pSprite->setPosition( ccp(size.width/2, size.height/2) );  
  76.   
  77.     // add the sprite as a child to this layer  
  78.     this->addChild(pSprite, 0);  
  79.       
  80.     // JNI call test  
  81. #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) //判断当前是否为Android平台  
  82.     JniMethodInfo minfo;//定义Jni函数信息结构体  
  83.     //getStaticMethodInfo 次函数返回一个bool值表示是否找到此函数  
  84.     bool isHave = JniHelper::getStaticMethodInfo(minfo,"com/chen/FuckAndroid","JniTestFunction_Static""()V");  
  85.    
  86.     if (!isHave) {  
  87.         CCLog("jni:此函数不存在");  
  88.     }else{  
  89.         CCLog("jni:此函数存在");  
  90.         //调用此函数  
  91.         minfo.env->CallStaticVoidMethod(minfo.classID, minfo.methodID);  
  92.     }  
  93.     CCLog("jni-java函数执行完毕");  
  94. #endif  
  95.       
  96.       
  97.     return true;  
  98. }  
  99.   
  100. void HelloWorld::menuCloseCallback(CCObject* pSender)  
  101. {  
  102.     CCDirector::sharedDirector()->end();  
  103.   
  104. #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)  
  105.     exit(0);  
  106. #endif  
  107. }  

调用的方法在com.chen.FuckAndroid.java中

[java] view plaincopy
  1. /**************************************************************************** 
  2. Copyright (c) 2010-2012 cocos2d-x.org 
  3.  
  4. http://www.cocos2d-x.org 
  5.  
  6. Permission is hereby granted, free of charge, to any person obtaining a copy 
  7. of this software and associated documentation files (the "Software"), to deal 
  8. in the Software without restriction, including without limitation the rights 
  9. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
  10. copies of the Software, and to permit persons to whom the Software is 
  11. furnished to do so, subject to the following conditions: 
  12.  
  13. The above copyright notice and this permission notice shall be included in 
  14. all copies or substantial portions of the Software. 
  15.  
  16. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
  17. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
  18. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
  19. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
  20. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
  21. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
  22. THE SOFTWARE. 
  23. ****************************************************************************/  
  24. package com.chen;  
  25.   
  26. import org.cocos2dx.lib.Cocos2dxActivity;  
  27. import org.cocos2dx.lib.Cocos2dxEditText;  
  28. import org.cocos2dx.lib.Cocos2dxGLSurfaceView;  
  29. import org.cocos2dx.lib.Cocos2dxRenderer;  
  30.   
  31. import android.app.ActivityManager;  
  32. import android.content.Context;  
  33. import android.content.pm.ConfigurationInfo;  
  34. import android.os.Bundle;  
  35. import android.util.Log;  
  36. import android.widget.FrameLayout;  
  37. import android.view.ViewGroup;  
  38.   
  39. public class FuckAndroid extends Cocos2dxActivity{  
  40.   
  41.     protected void onCreate(Bundle savedInstanceState){  
  42.         super.onCreate(savedInstanceState);  
  43.           
  44.         if (detectOpenGLES20()) {  
  45.             // get the packageName,it's used to set the resource path  
  46.             String packageName = getApplication().getPackageName();  
  47.             super.setPackageName(packageName);  
  48.               
  49.             // FrameLayout  
  50.             ViewGroup.LayoutParams framelayout_params =  
  51.                 new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,  
  52.                                            ViewGroup.LayoutParams.FILL_PARENT);  
  53.             FrameLayout framelayout = new FrameLayout(this);  
  54.             framelayout.setLayoutParams(framelayout_params);  
  55.   
  56.             // Cocos2dxEditText layout  
  57.             ViewGroup.LayoutParams edittext_layout_params =  
  58.                 new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,  
  59.                                            ViewGroup.LayoutParams.WRAP_CONTENT);  
  60.             Cocos2dxEditText edittext = new Cocos2dxEditText(this);  
  61.             edittext.setLayoutParams(edittext_layout_params);  
  62.   
  63.             // ...add to FrameLayout  
  64.             framelayout.addView(edittext);  
  65.   
  66.             // Cocos2dxGLSurfaceView  
  67.             mGLView = new Cocos2dxGLSurfaceView(this);  
  68.   
  69.             // ...add to FrameLayout  
  70.             framelayout.addView(mGLView);  
  71.   
  72.             mGLView.setEGLContextClientVersion(2);  
  73.             mGLView.setCocos2dxRenderer(new Cocos2dxRenderer());  
  74.             mGLView.setTextField(edittext);  
  75.   
  76.             // Set framelayout as the content view  
  77.             setContentView(framelayout);  
  78.         }  
  79.         else {  
  80.             Log.d("activity""don't support gles2.0");  
  81.             finish();  
  82.         }     
  83.     }  
  84.       
  85.      @Override  
  86.      protected void onPause() {  
  87.          super.onPause();  
  88.          mGLView.onPause();  
  89.      }  
  90.   
  91.      @Override  
  92.      protected void onResume() {  
  93.          super.onResume();  
  94.          mGLView.onResume();  
  95.      }  
  96.        
  97.      private boolean detectOpenGLES20()   
  98.      {  
  99.          ActivityManager am =  
  100.                 (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);  
  101.          ConfigurationInfo info = am.getDeviceConfigurationInfo();  
  102.          return (info.reqGlEsVersion >= 0x20000);  
  103.      }  
  104.        
  105.      //////////////////////////  
  106.      // These functions will be called by C++ code  
  107.      public static void JniTestFunction_Static(){  
  108.          System.out.println("JniTestFunction_Static_Called");  
  109.      }  
  110.      public void JniTestFunction(){  
  111.          System.out.println("JniTestFunction_Called");  
  112.      }  
  113.      /////////////////////////  
  114.        
  115.      static {  
  116.          System.loadLibrary("game");  
  117.      }  
  118. }  

调用结果:



0 0
原创粉丝点击